Hans Mackowiak wrote in post #1119151:
#respond_to_missing? is needed when you want to use #method_missing with
#method
From some efforts I put,I can tell you that #respond_to_missing? is no
way connected to the method #method_missing,rather it works with
#respond_to? .
class Foo
def respond_to_missing?(meth,include_private = false)
"I am being called by #respond_to?"
end
def baz
"I do exist"
end
end
foo = Foo.new
foo.respond_to?(:baz)
# => true
foo.respond_to?(:bar)
# => true # probably `respond_to_missing?` returns the truth value of
the object,rather the object.
See again:-
class Foo
def respond_to_missing?(meth,include_private = false)
nil
end
def baz
"I do exist"
end
end
foo = Foo.new
foo.respond_to?(:baz) # => true
foo.respond_to?(:bar) # => false
**method_missing**
class Foo
def method_missing(meth)
"#{meth} not found"
end
end
foo = Foo.new
foo.bar
# => "bar not found"
foo.method(:bar)
# ~> -:8:in `method': undefined method `bar' for class `Foo' (NameError)
# ~> from -:8:in `<main>'
Now to handle this error I think I need to override the method
#respond_to_missing? .
class Foo
def respond_to_missing?(meth,include_private = false)
p "checking if I am being called or not"
end
def baz
"I do exist"
end
def method_missing(meth)
"#{meth} not found"
end
end
foo = Foo.new
foo.bar
# => "bar not found"
foo.method(:bar)
# >> "checking if I am being called or not"
conclusions :-
From this examples I can think of 2 situations,where I should override
the method `#method_missing` and `respond_to_missing?`.
Any other cases do you guys wanted me to point,when I must need to think
of `method_missing` or `respond_to_missing?` to override ? Obviously
overriding both of them cool way to handle any errors.
···
--
Posted via http://www.ruby-forum.com/\.