使用多个模块扩展的对象中方法的Ruby优先级 [英] Ruby precedence of methods in objects extended with multiple modules
问题描述
给出以下内容:
class User; attr_accessor :roles; end
module RegisteredUser
def default_context
Submission
end
end
module Admin
def default_context
Review
end
end
current_user = User.new
current_user.roles = ["registered_user", "admin"]
current_user.roles.each do |role|
role_module = role.gsub(/ /, '_').camelize
if module_exists?(role_module)
current_user.extend role_module.constantize
end
end
context = self.extend current_user.default_context
是否可以设置User#default_context
的优先级?也就是说,无论current_user
的扩展顺序如何,Admin#default_context
始终优先于RegisteredUser#default_context
?
Is there a way to set the priority of User#default_context
? That is, can I say that the Admin#default_context
always takes priority over RegisteredUser#default_context
regardless of the order in which current_user
is extended?
推荐答案
method_added
在Module
中.
我的意思实际上是included
,而不是extended
,但是两者都在Module
中.
I actually meant included
, not extended
, but both are also in Module
.
该机制将围绕执行以下操作:
The mechanism would revolve around doing something like this:
module Foo
def self.included(base)
base.extend(FooMethods)
end
module FooMethods
def bar
# Whatever
end
end
end
在Foo.included
内部,您可以根据任意标准确定是否应将相关方法添加到base
(包括模块的实体)中.
Inside Foo.included
you can determine, based on arbitrary criteria, whether or not the methods in question should be added to base
(the entity including the module).
在您的情况下,您可以检查是否已包含更高优先级"模块,或者查看模块是否是更高优先级"模块.基于此,您将决定是否添加方法.
In your case, you could check to see if a "higher priority" module was already included, or see if the module is the "higher priority" module. Based on that you'd decide whether or not to add the methods.
这篇关于使用多个模块扩展的对象中方法的Ruby优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!