Ruby包含模块中模块的单一方法 [英] Ruby include module's single method in model
问题描述
我有以下模块
module SimpleTask
def task1
end
def task2
end
def task3
end
end
我有一个模型只需要 task2
模块的方法 SimpleTask
。
And I have a model which requires only task2
method of module SimpleTask
.
我知道在我的模型中包含 SimpleTask
,其中包含 include SimpleTask
可以完成这项工作。
I know including SimpleTask
in my model with include SimpleTask
would do the job.
但我想知道我的模型中是否只能包含特定的 task2
方法。
But I wonder if I can only include specific task2
method in my model.
推荐答案
听起来你需要将#task2
重构成一个单独的模块(例如, BaseTask
)。然后你可以轻松地只包含 BaseTask
,你只需要#task2
。
It sounds like you need to refactor #task2
into a separate module (e.g., BaseTask
). Then you can easily include only BaseTask
where you only need #task2
.
module BaseTask
def task2
...
end
end
module SimpleTask
include BaseTask
def task1
...
end
def task3
...
end
end
如果没有更具体的问题(比如两者之间的相互依赖),很难提供更多帮助 SimpleTask
等的方法
It's hard to help much more without a more concrete question (such as interdependence between the methods of SimpleTask
, etc.
你可以做一些元编程包括SimpleTask
然后取消定义你不想要的方法,但这是非常难看的IMO。
You could do some meta-programming where you include SimpleTask
and then undefine the methods you don't want, but that's pretty ugly IMO.
这篇关于Ruby包含模块中模块的单一方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!