Module: ModelCached::ClassMethods
- Defined in:
- lib/model_cached.rb
Instance Method Summary collapse
- #cache_by(*column_names) ⇒ Object
- #find_cached_by(column, value) ⇒ Object
- #mc_key(column, value, scope_key = nil) ⇒ Object
- #mc_scope_key ⇒ Object
Instance Method Details
#cache_by(*column_names) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/model_cached.rb', line 7 def cache_by(*column_names) = {logical_delete: nil, scope: nil}.merge(column_names.) [:columns] = column_names after_save :refresh_mc_keys after_touch :refresh_mc_keys after_destroy :expire_mc_keys class_eval %{ def self.mc_options; #{}; end } column_names.each do |column| class_eval %{ def self.find_by_#{column}(value); find_cached_by(#{column.to_s.inspect}, value); end } end if column_names.include?(:id) class_eval do def self.find(*args) if args.size == 1 and (id = args.first).is_a?(Integer) find_by_id(id) || raise(ActiveRecord::RecordNotFound, "Couldn't find #{name} with ID=#{id}") else super(*args) end end end end include ModelCached::InstanceMethods end |
#find_cached_by(column, value) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/model_cached.rb', line 31 def find_cached_by(column, value) if [:scope] and mc_scope_key.nil? where(column => value).first else Rails.cache.fetch(mc_key(column, value)) { where(column => value).first } end end |
#mc_key(column, value, scope_key = nil) ⇒ Object
43 44 45 |
# File 'lib/model_cached.rb', line 43 def mc_key(column, value, scope_key=nil) [column, value, scope_key || mc_scope_key].unshift(self.name.tableize).compact.join('/').gsub(/\s+/, '+') end |
#mc_scope_key ⇒ Object
39 40 41 |
# File 'lib/model_cached.rb', line 39 def mc_scope_key self.new().mc_scope_key end |