Skip to content
This repository
Browse code

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...
commit 757f7231cccd2bcbfb83fba5cb203fb320f3e613 1 parent df2104e
Joost Baaij authored March 13, 2012 carlosantoniodasilva committed June 18, 2012
6  activerecord/CHANGELOG.md
Source Rendered
... ...
@@ -1,5 +1,11 @@
1 1
 ## Rails 4.0.0 (unreleased) ##
2 2
 
  3
+*   Added a `stored_attributes` hash which contains the attributes stored
  4
+    using ActiveRecord::Store. This allows you to retrieve the list of
  5
+    attributes you've defined.
  6
+
  7
+    *Joost Baaij*
  8
+
3 9
 *   `composed_of` was removed. You'll have to write your own accessor
4 10
     and mutator methods if you'd like to use value objects to represent some
5 11
     portion of your models. So, instead of:
12  activerecord/lib/active_record/store.rb
... ...
@@ -1,3 +1,4 @@
  1
+require 'active_support/concern'
1 2
 require 'active_support/core_ext/hash/indifferent_access'
2 3
 
3 4
 module ActiveRecord
@@ -33,9 +34,18 @@ module ActiveRecord
33 34
   #   class SuperUser < User
34 35
   #     store_accessor :settings, :privileges, :servants
35 36
   #   end
  37
+  #
  38
+  # The stored attribute names can be retrieved using +stored_attributes+.
  39
+  #
  40
+  #   User.stored_attributes[:settings] # [:color, :homepage]
36 41
   module Store
37 42
     extend ActiveSupport::Concern
38 43
 
  44
+    included do
  45
+      config_attribute :stored_attributes
  46
+      self.stored_attributes = {}
  47
+    end
  48
+
39 49
     module ClassMethods
40 50
       def store(store_attribute, options = {})
41 51
         serialize store_attribute, IndifferentCoder.new(options[:coder])
@@ -55,6 +65,8 @@ def store_accessor(store_attribute, *keys)
55 65
             send(store_attribute)[key]
56 66
           end
57 67
         end
  68
+
  69
+        self.stored_attributes[store_attribute] = keys.flatten
58 70
       end
59 71
     end
60 72
 
6  activerecord/test/cases/store_test.rb
@@ -13,7 +13,7 @@ class StoreTest < ActiveRecord::TestCase
13 13
     assert_equal 'black', @john.color
14 14
     assert_nil @john.homepage
15 15
   end
16  
-  
  16
+
17 17
   test "writing store attributes through accessors" do
18 18
     @john.color = 'red'
19 19
     @john.homepage = '37signals.com'
@@ -111,4 +111,8 @@ class StoreTest < ActiveRecord::TestCase
111 111
     @john.is_a_good_guy = false
112 112
     assert_equal false, @john.is_a_good_guy
113 113
   end
  114
+
  115
+  test "stored attributes are returned" do
  116
+    assert_equal [:color, :homepage], Admin::User.stored_attributes[:settings]
  117
+  end
114 118
 end

0 notes on commit 757f723

Please sign in to comment.
Something went wrong with that request. Please try again.