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

标签 ruby class module call

我有 2 个模块和 1 个类:

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 ???"

我怎样才能从 B 收到 hi 的消息?

最佳答案

可以使用caller_locations确定调用方法的名称,并使用该信息检索方法的 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

关于ruby - 如何知道调用了哪个模块用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35482918/

相关文章:

ruby - 与 Faye 和 Rails 的私信

c++ - 当派生类添加了数据成员时,派生类的构造函数应该如何在 C++ 中使用

import - ES2015 `import * as` 与普通 `import` 之间的区别

C++从成员指针转换回持有类指针

module - 在创建单独的模块过程时,在什么情况下您会在子模块中使用 "module procedure"?

linux - 将代码和数据放入 Linux 内核模块中的同一部分

ruby - 正则表达式错误 : too many multibyte code ranges are specified

ruby - "Missing master key"使用密码箱

ruby - apt Recipe 不会安装在我的 Recipe 中

c++ - Sprite 不会在 SFML 中移动