Crystal: Feature Request: public_method_defined?

Created on 22 Sep 2015  路  6Comments  路  Source: crystal-lang/crystal

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 ?

feature compiler

Most helpful comment

I think responds_to? should return false if the method is not callable from the current context.

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings