Browse files

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.
  • Loading branch information...
1 parent df2104e commit 757f7231cccd2bcbfb83fba5cb203fb320f3e613 @tilsammans tilsammans committed with carlosantoniodasilva Mar 13, 2012
Showing with 23 additions and 1 deletion.
  1. +6 −0 activerecord/CHANGELOG.md
  2. +12 −0 activerecord/lib/active_record/store.rb
  3. +5 −1 activerecord/test/cases/store_test.rb
View
6 activerecord/CHANGELOG.md
@@ -1,5 +1,11 @@
## 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.
+
+ *Joost Baaij*
+
* `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
portion of your models. So, instead of:
View
12 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 @@ def store_accessor(store_attribute, *keys)
send(store_attribute)[key]
end
end
+
+ self.stored_attributes[store_attribute] = keys.flatten
end
end
View
6 activerecord/test/cases/store_test.rb
@@ -13,7 +13,7 @@ class StoreTest < ActiveRecord::TestCase
assert_equal 'black', @john.color
assert_nil @john.homepage
end
-
+
test "writing store attributes through accessors" do
@john.color = 'red'
@john.homepage = '37signals.com'
@@ -111,4 +111,8 @@ class StoreTest < ActiveRecord::TestCase
@john.is_a_good_guy = false
assert_equal false, @john.is_a_good_guy
end
+
+ test "stored attributes are returned" do
+ assert_equal [:color, :homepage], Admin::User.stored_attributes[:settings]
+ end
end

0 comments on commit 757f723

Please sign in to comment.