Skip to content
Browse files

Dynamically generate reader methods for serialized attributes. Closes #…

…6362.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@5416 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent ea433f1 commit c7c3994d31322a00ab591b9365da5ca63dccaa90 @jeremy jeremy committed
Showing with 22 additions and 4 deletions.
  1. +2 −0 activerecord/CHANGELOG
  2. +19 −3 activerecord/lib/active_record/base.rb
  3. +1 −1 activerecord/test/base_test.rb
View
2 activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes]
+
* Deprecation: object transactions warning. [Jeremy Kemper]
* has_one :dependent => :nullify ignores nil associates. #6528 [janovetz, Jeremy Kemper]
View
22 activerecord/lib/active_record/base.rb
@@ -1874,9 +1874,16 @@ def read_attribute_before_type_cast(attr_name)
# ActiveRecord::Base.generate_read_methods is set to true.
def define_read_methods
self.class.columns_hash.each do |name, column|
- unless self.class.serialized_attributes[name]
- define_read_method(name.to_sym, name, column) unless respond_to_without_attributes?(name)
- define_question_method(name) unless respond_to_without_attributes?("#{name}?")
+ unless respond_to_without_attributes?(name)
+ if self.class.serialized_attributes[name]
+ define_read_method_for_serialized_attribute(name)
+ else
+ define_read_method(name.to_sym, name, column)
+ end
+ end
+
+ unless respond_to_without_attributes?("#{name}?")
+ define_question_method(name)
end
end
end
@@ -1894,6 +1901,15 @@ def define_read_method(symbol, attr_name, column)
evaluate_read_method attr_name, "def #{symbol}; #{access_code}; end"
end
+ # Define read method for serialized attribute.
+ def define_read_method_for_serialized_attribute(attr_name)
+ unless attr_name.to_s == self.class.primary_key.to_s
+ self.class.read_methods << attr_name
+ end
+
+ evaluate_read_method attr_name, "def #{attr_name}; unserialize_attribute('#{attr_name}'); end"
+ end
+
# Define an attribute ? method.
def define_question_method(attr_name)
unless attr_name.to_s == self.class.primary_key.to_s
View
2 activerecord/test/base_test.rb
@@ -1476,7 +1476,7 @@ def test_to_param_should_return_string
private
def assert_readers(model, exceptions)
- expected_readers = Set.new(model.column_names - (model.serialized_attributes.keys + ['id']))
+ expected_readers = Set.new(model.column_names - ['id'])
expected_readers += expected_readers.map { |col| "#{col}?" }
expected_readers -= exceptions
assert_equal expected_readers, model.read_methods

0 comments on commit c7c3994

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