Hi,
The following code fails at compile time:
class Foo
def foo
puts "Foo"
end
private def bar
puts "Bar"
end
end
f = Foo.new
puts "Responds to foo: #{f.responds_to?(:foo)}"
puts "Responds to bar: #{f.responds_to?(:bar)}"
f.foo
f.bar
Error in ./test.cr:16: private method 'bar' called for Foo
Ruby has the public_method_defined? method for checking if the required method exists and can be called from another object. Is this something that can be implemented into crystal ?
What if you wrap it?
if f.responds_to?(:bar)
f.bar
end
No, same compile error:
class Foo
def foo
puts "Foo"
end
private def bar
puts "Bar"
end
end
f = Foo.new
if f.responds_to?(:foo)
puts "it responds to foo"
f.foo
end
if f.responds_to?(:bar)
puts "it responds to bar"
f.bar
end
######
#Error in ./test2.cr:20: private method 'bar' called for Foo
# f.bar
I think responds_to? should return false if the method is not callable from the current context.
I agree with @jhass
I think this issue could be closed in favour of #2549?
Let's close in favour of #2549
Most helpful comment
I think
responds_to?should return false if the method is not callable from the current context.