Class: SmartCollection::ScopeBuilder
- Inherits:
-
Object
- Object
- SmartCollection::ScopeBuilder
- Defined in:
- lib/smart_collection/scope_builder.rb
Instance Method Summary collapse
- #build ⇒ Object
- #bulk_load ⇒ Object
-
#initialize(rule, klass) ⇒ ScopeBuilder
constructor
A new instance of ScopeBuilder.
- #rule_to_bulk_queries(rule) ⇒ Object
- #rule_to_scope(rule) ⇒ Object
Constructor Details
#initialize(rule, klass) ⇒ ScopeBuilder
Returns a new instance of ScopeBuilder.
3 4 5 6 7 |
# File 'lib/smart_collection/scope_builder.rb', line 3 def initialize rule, klass @rule = rule @klass = klass @klass_hash = {} end |
Instance Method Details
#build ⇒ Object
9 10 11 12 13 |
# File 'lib/smart_collection/scope_builder.rb', line 9 def build rule_to_bulk_queries @rule bulk_load rule_to_scope @rule end |
#bulk_load ⇒ Object
15 16 17 18 19 |
# File 'lib/smart_collection/scope_builder.rb', line 15 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
21 22 23 24 25 26 27 28 29 |
# File 'lib/smart_collection/scope_builder.rb', line 21 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
31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/smart_collection/scope_builder.rb', line 31 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 |