From 0306e4a20483a91d9288ac6f20e6b79db6eca7a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20L=C3=BCtke?= Date: Fri, 4 May 2007 20:07:37 +0000 Subject: Make respond_to? work as expected git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6657 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activeresource/lib/active_resource/base.rb | 20 ++++++++++++++++++++ activeresource/test/base_test.rb | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index d2253186b0..0f147acad9 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -316,6 +316,26 @@ module ActiveResource end self end + + # For checking respond_to? without searching the attributes (which is faster). + alias_method :respond_to_without_attributes?, :respond_to? + + # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and + # person.respond_to?("name?") which will all return true. + def respond_to?(method, include_priv = false) + method_name = method.to_s + if attributes.nil? + return super + elsif attributes.has_key?(method_name) + return true + elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1)) + return true + end + # super must be called at the end of the method, because the inherited respond_to? + # would return true for generated readers, even if the attribute wasn't present + super + end + protected def connection(refresh = false) diff --git a/activeresource/test/base_test.rb b/activeresource/test/base_test.rb index 6a6ee5c64b..e9bf5d70b3 100644 --- a/activeresource/test/base_test.rb +++ b/activeresource/test/base_test.rb @@ -178,6 +178,14 @@ class BaseTest < Test::Unit::TestCase assert_kind_of Person, matz assert_equal "Matz", matz.name end + + def test_respond_to + matz = Person.find(1) + assert matz.respond_to?(:name) + assert matz.respond_to?(:name=) + assert matz.respond_to?(:name?) + assert !matz.respond_to?(:java) + end def test_find_by_id_with_custom_prefix addy = StreetAddress.find(1, :params => { :person_id => 1 }) -- cgit v1.2.3