class AttributeCache::AttributeCache
Public Class Methods
new(name:, attribute:, callback:)
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 3 def initialize(name:, attribute:, callback:) @name = name @attribute = attribute @callback = callback end
Public Instance Methods
set_attribute(record, save: false, args: [])
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 9 def set_attribute(record, save: false, args: []) record.write_attribute(@attribute, execute_callback(record, *args)) record.save if save end
Also aliased as: invalidate_attribute
set_attribute!(record, args: [])
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 15 def set_attribute!(record, args: []) set_attribute(record, save: true, args: args) end
Also aliased as: invalidate_attribute!
value(record, save:, keep_blanks:, args: [])
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 20 def value(record, save:, keep_blanks:, args: []) if cached_value(record).nil? || !keep_blanks && cached_value(record).blank? set_attribute(record, save: save, args: args) end cached_value(record) end
Private Instance Methods
cached_value(record)
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 29 def cached_value(record) record.read_attribute(@attribute) end
execute_callback(record, *args)
click to toggle source
# File lib/attribute_cache/attribute_cache.rb, line 33 def execute_callback(record, *args) case @callback when Symbol, String record.send(@callback, *args) when Proc @callback[*args] else raise 'An invalid callback was provided!' end end