Module: Queries::Annotator

Includes:
Arel::Nodes
Defined in:
lib/queries/annotator.rb

Overview

Methods to facilitate permission and handling of polymorphic relationships

Class Method Summary (collapse)

Class Method Details

+ (Arel::Nodes::And) annotator_params(params, klass)

Returns for use in SomeAnnotator.where()

Returns:

  • (Arel::Nodes::And)

    for use in SomeAnnotator.where()



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/queries/annotator.rb', line 52

def self.annotator_params(params, klass)
  t = klass.arel_table

  c = [ polymorphic_params(params, klass) ]

  c.push t[:created_at].lteq(Date.new(*params[:created_before].split('-').map(&:to_i))) if params[:created_before]
  c.push t[:created_at].gteq(Date.new(*params[:created_after].split('-').map(&:to_i))) if params[:created_after]

  c.push t[klass.annotator_type].eq_any(params[:on]) if params[:on]
  c.push t[:id].eq_any(params[:id]) if params[:id]
  c.push t[:created_by_id].eq_any(params[:by]) if params[:by]

  c.compact!

  w = c.pop

  c.each do |q|
    w = w.and(q)
  end

  w
end

+ (Array of Arel::Nodes::And) polymorphic_nodes(hash, klass)

Returns:

  • (Array of Arel::Nodes::And)


11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/queries/annotator.rb', line 11

def self.polymorphic_nodes(hash, klass)
  return nil if hash.empty?
  t = klass.arel_table
  nodes = []
  hash.keys.each do |k|
    model = k.to_s.gsub(/_id$/, '').camelize
    nodes.push(
      t[klass.annotator_id].eq(hash[k]).and(t[klass.annotator_type].eq(model))
    )
  end
  nodes
end

+ (Arel::Nodes::And) polymorphic_params(params, klass)

TODO: rename

Returns:

  • (Arel::Nodes::And)

    translates params from requests like `otus/123/data_attributes` to a Arel::Nodes::And clause equvialent to `DataAttribute.where(attribute_subject_type: 'Otu', attribute_subject_id: 123)`



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/queries/annotator.rb', line 31

def self.polymorphic_params(params, klass)
  t = klass.arel_table

  # TODO- remove this? Force the filter up to controller? i.e. in `filter_params`?
  h = params.permit(klass.related_foreign_keys).to_h
  
  return nil if h.size != 1

  a = polymorphic_nodes(h, klass)
  n = a.shift
  a.each do |b|
    n = n.and(b)
  end
  n
end