我有 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/