Class: SmartCollection::Mixin
- Inherits:
-
Module
- Object
- Module
- SmartCollection::Mixin
- Defined in:
- lib/smart_collection/mixin.rb
Defined Under Namespace
Modules: ClassMethods, InstanceMethods
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
Instance Method Summary collapse
- #cached_scope(owner) ⇒ Object
- #included(base) ⇒ Object
-
#initialize(raw_config) ⇒ Mixin
constructor
A new instance of Mixin.
- #uncached_scope(owner) ⇒ Object
Constructor Details
#initialize(raw_config) ⇒ Mixin
Returns a new instance of Mixin.
31 32 33 |
# File 'lib/smart_collection/mixin.rb', line 31 def initialize raw_config @raw_config = raw_config end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
29 30 31 |
# File 'lib/smart_collection/mixin.rb', line 29 def config @config end |
Instance Method Details
#cached_scope(owner) ⇒ Object
39 40 41 |
# File 'lib/smart_collection/mixin.rb', line 39 def cached_scope owner @config.cache_manager.read_scope owner end |
#included(base) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/smart_collection/mixin.rb', line 43 def included base @config = config = SmartCollection::Config.new(@raw_config) = {smart_collection: config} if config.item_class_name [:class_name] = config.item_class_name end base.include(InstanceMethods) base.extend(ClassMethods) if cache_class = CacheManager.determine_class(@raw_config) config.cache_manager = cache_class.new(model: base, config: config) end = { name: config.items_name, scope: -> owner { if cache_manager = config.cache_manager unless cache_manager.cache_exists? owner owner.update_cache end cached_scope(owner) else uncached_scope(owner) end }, type: :collection } case when cache_class == SmartCollection::CacheManager::CacheStore [:preloader] = -> owners { owners.reject(&:cache_exists?).each(&:update_cache) loaded = config.cache_manager.read_multi(owners) records = config.item_class.where(id: loaded.values.flatten.uniq).map{|x| [x.id, x]}.to_h loaded.map do |owner, ids| [owner, ids.map{|x| records[x]}] end.to_h } when cache_class == SmartCollection::CacheManager::Table cached_name = "cached_#{config.items_name}".to_sym [:preloader] = -> owners { owners.reject(&:cache_exists?).each(&:update_cache) Associationist.preload(owners, cached_items: config.item_name) owners.map do |owner| [owner, owner.cached_items.map{|item| item.send(config.item_name)}] end.to_h } else [:preloader] = -> _ { raise RuntimeError, "Turn on cache to enable preloading." } end base.include Associationist::Mixin.new() base.validates_with SmartCollection::Validator end |
#uncached_scope(owner) ⇒ Object
35 36 37 |
# File 'lib/smart_collection/mixin.rb', line 35 def uncached_scope owner SmartCollection::ScopeBuilder.new(owner.rule, @config.item_class).build end |