module AttributeCache
Constants
- VERSION
Public Class Methods
attribute_cache(name, options = {}, &block)
click to toggle source
# File lib/attribute_cache.rb, line 10 def self.attribute_cache(name, options = {}, &block) options.default! :attribute_prefix, 'cached' options.default! :callback_prefix, 'calculate' options.default! :attribute, :"#{options[:attribute_prefix]}_#{name}" options.default! :callback, :"#{options[:callback_prefix]}_#{name}" options[:callback] = block if block_given? options.default! :cache_on_create, false options.default! :dependent_on, [] options[:dependent_on] = [options[:dependent_on]] unless options[:dependent_on].is_a? Array attr_cache = AttributeCache.new( name: name, attribute: options[:attribute], callback: options[:callback] ) if options[:cache_on_create] before_create(if: -> { read_attribute(options[:attribute]).nil? }) do attr_cache.set_attribute(self) end end if options[:dependent_on].count.positive? before_update(if: -> { dependent_attribute_will_change(self, options[:dependent_on]) }) do attr_cache.invalidate_attribute(self) end end define_method("set_#{name}") do |save: false, args: []| attr_cache.set_attribute(self, save: save, args: args) end define_method("invalidate_#{name}") do |save: false, args: []| attr_cache.invalidate_attribute(self, save: save, args: args) end define_method("set_#{name}!") do |args: []| attr_cache.set_attribute!(self, args: args) end define_method("invalidate_#{name}!") do |args: []| attr_cache.invalidate_attribute!(self, args: args) end define_method(name) do |save: true, keep_blanks: true, args: []| attr_cache.value(self, save: save, keep_blanks: keep_blanks, args: args) end end
attribute_store(name, options = {}, &block)
click to toggle source
# File lib/attribute_cache.rb, line 63 def self.attribute_store(name, options = {}, &block) options.default! :cache_on_create, true options.default! :attribute_prefix, 'stored' attribute_cache(name, options, &block) end
Private Instance Methods
dependent_attribute_will_change(record, dependent_on)
click to toggle source
# File lib/attribute_cache.rb, line 73 def dependent_attribute_will_change(record, dependent_on) dependent_on.any? { |d| record.will_save_change_to_attribute?(d) } end