Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

respond_to? and protected methods

It may not be so obvious how respond_to? works in ruby. Consider that:


class A

   def public_method
   end

   protected
   def protected_method
   end

   private
   def private_method
   end

end

obj = A.new
obj.respond_to?(:public_method)
# true - that's pretty obvious
obj.respond_to?(:private_method)
# false - as expected
obj.respond_to?(:protected_method)
# true - WTF?

So if 'obj' responds to protected_method we should expect

obj.protected_method

not to raise an exception, shouldn't we?

...but it raises obviously

Documentation points that calling respond_to? with 2nd argument set to true check private method as well

obj.respond_to?(:private_method, true)
# true

And that's far more reasonable

So the question is how to check if object responds to public method only? Is there a solution better than that?

obj.methods.include?(:public_method)
# true
obj.methods.include?(:protected_method)
# false
like image 351
mlomnicki Avatar asked Apr 02 '10 22:04

mlomnicki


1 Answers

From the documentation:

Returns true if obj responds to the given method. Private and protected methods are included in the search only if the optional second parameter evaluates to true

When the question was written (Ruby 1.8.7):

Returns true if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

like image 70
wanghao Avatar answered Oct 12 '22 11:10

wanghao