Class: Pickel::Condition

Inherits:
Object
  • Object
show all
Defined in:
lib/pickel/condition.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass:, predicate:, column: nil, target: nil, join_tables: []) ⇒ Condition

Returns a new instance of Condition.



16
17
18
19
20
21
22
# File 'lib/pickel/condition.rb', line 16

def initialize(klass:, predicate:, column: nil, target: nil, join_tables: [])
  @klass = klass
  @predicate = predicate
  @column = column
  @target = target
  @join_tables = join_tables
end

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



23
24
25
# File 'lib/pickel/condition.rb', line 23

def column
  @column
end

#join_tablesObject (readonly)

Returns the value of attribute join_tables.



23
24
25
# File 'lib/pickel/condition.rb', line 23

def join_tables
  @join_tables
end

#klassObject (readonly)

Returns the value of attribute klass.



23
24
25
# File 'lib/pickel/condition.rb', line 23

def klass
  @klass
end

#predicateObject (readonly)

Returns the value of attribute predicate.



23
24
25
# File 'lib/pickel/condition.rb', line 23

def predicate
  @predicate
end

#targetObject (readonly)

Returns the value of attribute target.



23
24
25
# File 'lib/pickel/condition.rb', line 23

def target
  @target
end

Class Method Details

.for(klass, key) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/pickel/condition.rb', line 6

def for(klass, key)
  s_key = key.to_s
  predicate = Predicate.find(s_key)

  cond = new(klass: klass, predicate: predicate)
  new_key = s_key.delete_suffix("_#{predicate.id}")
  cond.assign_column(new_key)
end

Instance Method Details

#assign_column(key, target: klass, join_tables: []) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/pickel/condition.rb', line 25

def assign_column(key, target: klass, join_tables: [])
  base = { klass: klass, predicate: predicate, target: target, join_tables: join_tables }
  return Condition.new(base.merge(column: key)) if target.attribute_names.include?(key)

  association = target.reflect_on_all_associations.find { |a| key.start_with?(a.name.to_s) }
  if association
    new_key = key.delete_prefix("#{association.name}_")
    join_tables << association.name
    new_target = association.klass

    assign_column(new_key, target: new_target, join_tables: join_tables)
  else
    Condition.new(base.merge(predicate: nil))
  end
end

#build(value) ⇒ Object



41
42
43
44
45
46
# File 'lib/pickel/condition.rb', line 41

def build(value)
  return klass.all if predicate.nil?

  rel = predicate.build(target, column, value)
  join_tables.empty? ? rel : join_relation.merge(rel)
end