如何知道调用了哪个模块用户

How to know from what module user was called

我有 2 个模块和 1 个 class:

module B
  def hi
    say 'hi'
  end
end

module C
  def say(message)
    puts "#{message} from ???"
  end
end

class A
  include B
  include C
end

A.new.hi
#=> hi from ???"

如何以 hi from B 的身份收到消息?

您可以使用 Kenel#__method__ with Method#owner:

module C
  def say(message)
    puts "#{message} from #{method(__method__).owner }"
  end
end

class A
  include C
end

A.new.say('hello')
#=> hello from C

Kenel#__method__:

Returns the name at the definition of the current method as a Symbol. If called outside of a method, it returns nil.

Method#owner:

Returns the class or module that defines the method.

可以使用caller_locations to determine the calling method's name, and use that information to retrieve the method's owner:

module C
  def say(message)
    method_name = caller_locations(1, 1)[0].base_label
    method_owner = method(method_name).owner
    puts "#{message} from #{method_owner}"
  end
end

但这很脆弱。简单地传递调用模块会容易得多,例如:

module B
  def hi
    say 'hi', B
  end
end

module C
  def say(message, mod)
    puts "#{message} from #{mod}"
  end
end