Skip to content

Instantly share code, notes, and snippets.

@kml
Last active August 29, 2015 14:26
Show Gist options
  • Save kml/834e836e9e2955f54479 to your computer and use it in GitHub Desktop.
Save kml/834e836e9e2955f54479 to your computer and use it in GitHub Desktop.
require "active_attr"
require "memoist"
class Model
include ActiveAttr::Model
extend Memoist
# by default ActiveAttr calls typecaster every time attribute reader is called
# this patch adds memoization
# https://github.com/cgriego/active_attr/blob/v0.8.5/lib/active_attr/attributes.rb#L199
def self.attribute!(name, options={})
attribute_definition = super
send(:memoize, attribute_definition.name)
define_method("#{attribute_definition.name}=") do |value|
result = super(value)
flush_cache(attribute_definition.name)
result
end
attribute_definition
end
attribute :number, typecaster: proc { |value| value * Time.now.to_f * 1000 }
end
require "minitest/autorun"
require "pry"
describe Model do
it "flushes cache on writer" do
m = Model.new(number: 1)
number1 = m.number
number1.wont_be_nil
m.number.must_equal number1
m.number = 5
number2 = m.number
number2.wont_be_nil
m.number.must_equal number2
number2.wont_equal number1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment