Skip to content
Browse files

Merge pull request #5064 from lest/patch-1

move id_before_type_cast to PrimaryKey module
  • Loading branch information...
2 parents eeae4da + ec4759d commit 079e2f4ec1c299424200f59b45bb2beae08d5966 @jeremy jeremy committed Feb 16, 2012
View
6 activerecord/lib/active_record/attribute_methods/before_type_cast.rb
@@ -20,11 +20,7 @@ def attributes_before_type_cast
# Handle *_before_type_cast for method_missing.
def attribute_before_type_cast(attribute_name)
- if attribute_name == 'id'
- read_attribute_before_type_cast(self.class.primary_key)
- else
- read_attribute_before_type_cast(attribute_name)
- end
+ read_attribute_before_type_cast(attribute_name)
end
end
end
View
11 activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -1,3 +1,5 @@
+require 'set'
+
module ActiveRecord
module AttributeMethods
module PrimaryKey
@@ -24,6 +26,11 @@ def id?
query_attribute(self.class.primary_key)
end
+ # Returns the primary key value before type cast
+ def id_before_type_cast
+ read_attribute_before_type_cast(self.class.primary_key)
+ end
+
protected
def attribute_method?(attr_name)
@@ -45,8 +52,10 @@ def id(v, attributes, attributes_cache, attr_name)
end
end
+ ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast).to_set
+
def dangerous_attribute_method?(method_name)
- super && !['id', 'id=', 'id?'].include?(method_name)
+ super && !ID_ATTRIBUTE_METHODS.include?(method_name)
end
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
View
8 activerecord/test/cases/attribute_methods_test.rb
@@ -121,6 +121,14 @@ def test_respond_to_with_custom_primary_key
assert keyboard.respond_to?('id')
end
+ def test_id_before_type_cast_with_custom_primary_key
+ keyboard = Keyboard.create
+ keyboard.key_number = '10'
+ assert_equal '10', keyboard.id_before_type_cast
+ assert_equal nil, keyboard.read_attribute_before_type_cast('id')
+ assert_equal '10', keyboard.read_attribute_before_type_cast('key_number')
+ end
+
# Syck calls respond_to? before actually calling initialize
def test_respond_to_with_allocated_object
topic = Topic.allocate

0 comments on commit 079e2f4

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