Ruby `response_to?` Doesn't work right after definition?

I have a module that defines a method, if not already defined. This applies to ActiveRecord attributes because their recipients and setters are not defined as methods.

module B
  def create_say_hello_if_not_exists
    puts respond_to?(:say_hello)
    define_method :say_hello do
      puts 'hello'
    end unless respond_to?(:say_hello)
  end
end

class A
  def say_hello
    puts 'hi'
  end
  puts respond_to?(:say_hello, true)
  extend B
  create_say_hello_if_not_exists
end

A.new.say_hello

Expected result hi, but ruby ​​prints hello. Why?

Perhaps related to Confused on "reply_to?" Method

+4
source share
2 answers

Try it.

module B
  def create_say_hello_if_not_exists
    puts method_defined?(:say_hello)
    define_method :say_hello do
      puts 'hello'
    end unless method_defined?(:say_hello)
  end
end

class A
  def say_hello
    puts 'hi'
  end
  puts method_defined?( :say_hello )
  extend B
  create_say_hello_if_not_exists
end

A.new.say_hello
+1
source

The reason it respond_to?(:say_hello)returns falseis due to the fact that it class Ahas say_helloan instance method, and as you extend class B, it is create_say_hello_if_not_existsdeclared as a class method and it does not find say_hello.

. say_hello class A .

module B
  def create_say_hello_if_not_exists
    puts respond_to?(:say_hello)
    define_method :say_hello do
      puts 'hello'
    end unless respond_to?(:say_hello)
  end
end

class A
  def self.say_hello
    puts 'hi'
  end
  extend B
  create_say_hello_if_not_exists
end

A.say_hello
0

Source: https://habr.com/ru/post/1568404/


All Articles