Class: SmartCollection::Associations::SmartCollectionAssociation::ScopeBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_collection/associations/smart_collection_association.rb

Instance Method Summary collapse

Constructor Details

#initialize(rule, klass) ⇒ ScopeBuilder

Returns a new instance of ScopeBuilder.



6
7
8
9
10
# File 'lib/smart_collection/associations/smart_collection_association.rb', line 6

def initialize rule, klass
  @rule = rule
  @klass = klass
  @klass_hash = {}
end

Instance Method Details

#buildObject



12
13
14
15
16
# File 'lib/smart_collection/associations/smart_collection_association.rb', line 12

def build
  rule_to_bulk_queries @rule
  bulk_load
  rule_to_scope @rule
end

#bulk_loadObject



18
19
20
21
22
# File 'lib/smart_collection/associations/smart_collection_association.rb', line 18

def bulk_load
  @klass_hash = @klass_hash.map do |klass_name, ids|
    [klass_name, Object.const_get(klass_name).where(id: ids).map{|x| [x.id, x]}.to_h]
  end.to_h
end

#rule_to_bulk_queries(rule) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/smart_collection/associations/smart_collection_association.rb', line 24

def rule_to_bulk_queries rule
  case
  when arr = (rule['or'] || rule['and'])
    arr.each{|x| rule_to_bulk_queries x}
  when assoc = rule['association']
    ids = @klass_hash[assoc['class_name']] ||= []
    ids << assoc['id']
  end
end

#rule_to_scope(rule) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/smart_collection/associations/smart_collection_association.rb', line 34

def rule_to_scope rule
  case
  when ors = rule['or']
    ors.map{|x| rule_to_scope x}.inject(:or)
  when ands = rule['and']
    ands.map{|x| rule_to_scope x}.inject(:merge)
  when assoc = rule['association']
    @klass_hash[assoc['class_name']][assoc['id']].association(assoc['source']).scope
  when cond = rule['condition']
    scope = @klass
    scope = scope.joins(cond['joins'].to_sym) if cond['joins']
    scope.where(cond['where'])
  end
end