diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 633198c4bb..10bfe1945a 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,10 +1,16 @@ ## Rails 4.0.0 (unreleased) ## -* Added a `stored_attributes` hash which contains the attributes stored - using ActiveRecord::Store. This allows you to retrieve the list of - attributes you've defined. +* Added `stored_attributes` hash which contains the attributes stored using + ActiveRecord::Store. This allows you to retrieve the list of attributes + you've defined. - *Joost Baaij* + class User < ActiveRecord::Base + store :settings, accessors: [:color, :homepage] + end + + User.stored_attributes[:settings] # [:color, :homepage] + + *Joost Baaij & Carlos Antonio da Silva* * `composed_of` was removed. You'll have to write your own accessor and mutator methods if you'd like to use value objects to represent some 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