Why do we need #respond_to_missing?


(Greg Navis) #1

Hi!

I was wondering why do we need #respond_to_missing? as a separate method. I
tried searching for a rationale in the Ruby bug tracker but couldn't find
it.

I don't understand how it's different from overriding #respond_to? to match
dynamic methods and calling super on other matches.

The answer I'm NOT looking for is that #method wouldn't work, etc. as this
is an answer to a different question ("Why do I need to override
#respond_to_missing?").

Why was Ruby designed in a way that introduces a distinction between
#respond_to? and #respond_to_missing? It feels like I'm overlooking
something simple.

Best regards
Greg Navis


(Victor Shepelev) #2

If you imagine Ruby to be entirely implemented in Ruby, we can
(simplistically) say, that those methods are defined as following:

public

def respond_to?(name)
  methods.include?(name) || respond_to_missing?(name)
end

private

def respond_to_missing?(name)
  false
end

Then, in your code, if you implement method_missing, you typically redefine
respond_to_missing? (fallback method) only, which is simpler.

If you overriding just respond_to_missing?, you can be as simple as:

def respond_to_missing?(name)
  name.match?(MY_SPECIAL_METHOD_PATTERN)
end

If you'd override respond_to? instead, you'll need to not forget to call
super, and be ready for performance implications. If you'll be to naive,
like

# You forgot to return true for method defined the "normal" way
def respond_to?(name)
  name.match?(MY_SPECIAL_METHOD_PATTERN)
end

...then some other code may break unexpectedly, which just tried to check
whether you object had #to_s (to write it in logs, for example).

Hope this helps.

V.

···

сб, 19 янв. 2019 г. в 13:41, Greg Navis <contact@gregnavis.com>:

Hi!

I was wondering why do we need #respond_to_missing? as a separate method.
I tried searching for a rationale in the Ruby bug tracker but couldn't find
it.

I don't understand how it's different from overriding #respond_to? to
match dynamic methods and calling super on other matches.

The answer I'm NOT looking for is that #method wouldn't work, etc. as this
is an answer to a different question ("Why do I need to override
#respond_to_missing?").

Why was Ruby designed in a way that introduces a distinction between
#respond_to? and #respond_to_missing? It feels like I'm overlooking
something simple.

Best regards
Greg Navis

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>


(Greg Navis) #3

Hi Victor!

Yes, that totally makes sense but is that the official reason for adding
it? Seems I can't find any conversations about it in Trac.

Best regards
Greg Navis