From 757f7231cccd2bcbfb83fba5cb203fb320f3e613 Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Tue, 13 Mar 2012 16:14:20 +0100 Subject: Remember the stored attributes in a config attribute. This allows you to retrieve the list of attributes you've defined. Usable for e.g. selects in the view, or interators based on the attributes you wish to store in the serialized column. --- activerecord/lib/active_record/store.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb index 542cb3187a..f5c7a9f034 100644 --- a/activerecord/lib/active_record/store.rb +++ b/activerecord/lib/active_record/store.rb @@ -1,3 +1,4 @@ +require 'active_support/concern' require 'active_support/core_ext/hash/indifferent_access' module ActiveRecord @@ -33,9 +34,18 @@ module ActiveRecord # class SuperUser < User # store_accessor :settings, :privileges, :servants # end + # + # The stored attribute names can be retrieved using +stored_attributes+. + # + # User.stored_attributes[:settings] # [:color, :homepage] module Store extend ActiveSupport::Concern + included do + config_attribute :stored_attributes + self.stored_attributes = {} + end + module ClassMethods def store(store_attribute, options = {}) serialize store_attribute, IndifferentCoder.new(options[:coder]) @@ -55,6 +65,8 @@ module ActiveRecord send(store_attribute)[key] end end + + self.stored_attributes[store_attribute] = keys.flatten end end -- cgit v1.2.3 From 8593964d9741704ff030e3bdf61e0ed64526ecec Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Fri, 25 May 2012 09:42:28 -0300 Subject: Refactor and use class_attribute --- activerecord/lib/active_record/store.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb index f5c7a9f034..d13491502e 100644 --- a/activerecord/lib/active_record/store.rb +++ b/activerecord/lib/active_record/store.rb @@ -1,5 +1,6 @@ require 'active_support/concern' require 'active_support/core_ext/hash/indifferent_access' +require 'active_support/core_ext/class/attribute' module ActiveRecord # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. @@ -42,7 +43,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - config_attribute :stored_attributes + class_attribute :stored_attributes self.stored_attributes = {} end @@ -53,7 +54,8 @@ module ActiveRecord end def store_accessor(store_attribute, *keys) - keys.flatten.each do |key| + keys = keys.flatten + keys.each do |key| define_method("#{key}=") do |value| initialize_store_attribute(store_attribute) send(store_attribute)[key] = value @@ -66,7 +68,7 @@ module ActiveRecord end end - self.stored_attributes[store_attribute] = keys.flatten + self.stored_attributes[store_attribute] = keys end end -- cgit v1.2.3