Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Remember the stored attributes in a config attribute. #5412

Closed
wants to merge 14 commits into
from
@@ -1,5 +1,9 @@
## 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 custom coders support for ActiveRecord::Store. Now you can set
your custom coder like this:
@@ -1,3 +1,5 @@
+require 'active_support/concern'
+
module ActiveRecord
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
# It's like a simple key/value store backed into your record when you don't care about being able to
@@ -30,9 +32,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, options.fetch(:coder, Hash)
@@ -52,6 +63,8 @@ def store_accessor(store_attribute, *keys)
send(store_attribute)[key.to_s]
end
end
+
+ self.stored_attributes[store_attribute] = keys.flatten
end
end
end
@@ -11,7 +11,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'
@@ -74,4 +74,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