From 46873aeded378bc836fb23925e5ab4f252f57b5b Mon Sep 17 00:00:00 2001 From: Matt Jones Date: Thu, 13 Sep 2012 10:12:11 -0400 Subject: refactor store_accessor --- activerecord/lib/active_record/store.rb | 44 ++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 6 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb index 8ea0ea239f..df7f58c81f 100644 --- a/activerecord/lib/active_record/store.rb +++ b/activerecord/lib/active_record/store.rb @@ -37,6 +37,28 @@ module ActiveRecord # The stored attribute names can be retrieved using +stored_attributes+. # # User.stored_attributes[:settings] # [:color, :homepage] + # + # == Overwriting default accessors + # + # All stored values are automatically available through accessors on the Active Record + # object, but sometimes you want to specialize this behavior. This can be done by overwriting + # the default accessors (using the same name as the attribute) and calling + # read_store_attribute(store_attribute_name, attr_name) and + # write_store_attribute(store_attribute_name, attr_name, value) to actually + # change things. + # + # class Song < ActiveRecord::Base + # # Uses a stored integer to hold the volume adjustment of the song + # store :settings, accessors: [:volume_adjustment] + # + # def volume_adjustment=(decibels) + # write_store_attribute(:settings, :volume_adjustment, decibels.to_i) + # end + # + # def volume_adjustment + # read_store_attribute(:settings, :volume_adjustment).to_i + # end + # end module Store extend ActiveSupport::Concern @@ -55,15 +77,11 @@ module ActiveRecord keys = keys.flatten keys.each do |key| define_method("#{key}=") do |value| - attribute = initialize_store_attribute(store_attribute) - if value != attribute[key] - send :"#{store_attribute}_will_change!" - attribute[key] = value - end + write_store_attribute(store_attribute, key, value) end define_method(key) do - initialize_store_attribute(store_attribute)[key] + read_store_attribute(store_attribute, key) end end @@ -72,6 +90,20 @@ module ActiveRecord end end + protected + def read_store_attribute(store_attribute, key) + attribute = initialize_store_attribute(store_attribute) + attribute[key] + end + + def write_store_attribute(store_attribute, key, value) + attribute = initialize_store_attribute(store_attribute) + if value != attribute[key] + send :"#{store_attribute}_will_change!" + attribute[key] = value + end + end + private def initialize_store_attribute(store_attribute) attribute = send(store_attribute) -- cgit v1.2.3