Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Delegate primary_key to superclass when necessary, otherwise default;…

… added testing
  • Loading branch information...
commit 265007e6148aa70f1f94a73f2f3cdcb8987b205a 1 parent b2fb5da
@DenzelMorris DenzelMorris authored
Showing with 46 additions and 1 deletion.
  1. +9 −1 lib/active_resource/base.rb
  2. +37 −0 test/cases/base_test.rb
View
10 lib/active_resource/base.rb
@@ -625,7 +625,15 @@ def collection_name
attr_writer :primary_key
def primary_key
- @primary_key ||= 'id'
+ if defined?(@primary_key)
+ @primary_key
+ elsif superclass != Object && superclass.primary_key
+ primary_key = superclass.primary_key
+ return primary_key if primary_key.is_a?(Symbol)
+ primary_key.dup.freeze
+ else
+ 'id'
+ end
end
# Gets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.json</tt>)
View
37 test/cases/base_test.rb
@@ -353,6 +353,43 @@ def test_timeout_reader_uses_superclass_timeout_until_written
assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class'
end
+ def test_primary_key_uses_superclass_primary_key_until_written
+ # Superclass is Object so defaults to 'id'
+ assert_equal 'id', ActiveResource::Base.primary_key
+ assert_equal 'id', Class.new(ActiveResource::Base).primary_key
+ Person.primary_key = :first
+
+ # Subclass uses superclass primary_key
+ actor = Class.new(Person)
+ assert_equal Person.primary_key, actor.primary_key
+
+ # Changing subclass primary_key doesn't change superclass primary_key
+ actor.primary_key = :second
+ assert_not_equal Person.primary_key, actor.primary_key
+
+ # Changing superclass primary_key doesn't overwrite subclass primary_key
+ Person.primary_key = :third
+ assert_not_equal Person.primary_key, actor.primary_key
+
+ # Changing superclass primary_key after subclassing changes subclass primary_key
+ jester = Class.new(actor)
+ actor.primary_key = :fourth
+ assert_equal actor.primary_key, jester.primary_key
+
+ # Subclass primary_keys are always equal to superclass primary_key when not overridden
+ fruit = Class.new(ActiveResource::Base)
+ apple = Class.new(fruit)
+
+ fruit.primary_key = :fifth
+ assert_equal fruit.primary_key, apple.primary_key, 'subclass did not adopt changes from parent class'
+
+ fruit.primary_key = :sixth
+ assert_equal fruit.primary_key, apple.primary_key, 'subclass did not adopt changes from parent class'
+
+ # Reset the primary key for subsequent tests
+ Person.primary_key = 'id'
+ end
+
def test_ssl_options_reader_uses_superclass_ssl_options_until_written
# Superclass is Object so returns nil.
assert_nil ActiveResource::Base.ssl_options
Please sign in to comment.
Something went wrong with that request. Please try again.