Skip to content

Commit

Permalink
Merge pull request rails#5064 from lest/patch-1
Browse files Browse the repository at this point in the history
move id_before_type_cast to PrimaryKey module
  • Loading branch information
jeremy committed Feb 16, 2012
2 parents eeae4da + ec4759d commit 079e2f4
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -1,3 +1,5 @@
require 'set'

module ActiveRecord
module AttributeMethods
module PrimaryKey
Expand All @@ -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)
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -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
Expand Down

0 comments on commit 079e2f4

Please sign in to comment.