Last active
January 4, 2017 20:40
-
-
Save tobiashm/7eb7931cb085ee93e33703be4f667799 to your computer and use it in GitHub Desktop.
Ruby special behaviour: `respond_to_missing?` method gets hidden
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# When you implement `method_missing` you should also implement `respond_to_missing?` | |
# But the later doesn't show up as instance methods on the class, and can not be called directly! Or does it??? | |
class Foo | |
def method_missing(name, *) | |
"called #{name}" | |
end | |
def bar? | |
respond_to_missing?(:bar) | |
end | |
# Defined as private in `Object` | |
def respond_to_missing?(*) | |
true | |
end | |
end | |
Foo.instance_methods(false) # => [:method_missing, :bar?] | |
foo = Foo.new | |
foo.bar # => "called bar" | |
foo.respond_to? :bar # => true | |
foo.respond_to_missing? :bar # => "called respond_to_missing?" | |
foo.private_methods(false) # => [:respond_to_missing?] | |
foo.send(:respond_to_missing?) # => true | |
foo.bar? # => true |
Updated update: I must have been calling self.respond_to_missing?
!
See e.g. http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated: I had some weird issues where I wasn't able to call
respond_to_missing?
even from other methods in the class. But it all seems to work now 😕