我可以在不包含Ruby模块的情况下调用它的实例方法吗?
我有一个声明许多实例方法的模块
I have a module which declares a number of instance methods
module UsefulThings
def get_file; ...
def delete_file; ...
def format_text(x); ...
end
我想从一个类中调用其中一些方法.通常在红宝石中的操作方式如下:
And I want to call some of these methods from within a class. How you normally do this in ruby is like this:
class UsefulWorker
include UsefulThings
def do_work
format_text("abc")
...
end
end
问题
include UsefulThings
从UsefulThings
引入了 all 个方法.在这种情况下,我只需要format_text
,而明确地不希望get_file
和delete_file
.
Problem
include UsefulThings
brings in all of the methods from UsefulThings
. In this case I only want format_text
and explicitly do not want get_file
and delete_file
.
我可以看到几种可能的解决方案:
I can see several possible solutions to this:
- 以某种方式直接在模块上调用方法,而无需在任何地方包含它
- 我不知道如何/是否可以做到这一点. (因此出现这个问题)
- Somehow invoke the method directly on the module without including it anywhere
- I don't know how/if this can be done. (Hence this question)
- 我也不知道如何/是否可以做到
- 这可以工作,但是匿名代理类是一种黑客.好吧.
- 这也将起作用,并且可能是我能想到的最好的解决方案,但是我宁愿避免使用它,因为这样最终会导致大量模块的扩散-管理该模块很麻烦
为什么单个模块中有许多不相关的功能?这是来自Rails应用程序的ApplicationHelper
,我们的团队事实上已将其确定为所有不够具体的东西的垃圾场.大多数情况下,独立的实用程序方法随处可见.我可以将其分解为单独的助手,但其中有30个,每个助手只有一种方法...这似乎没有用
Why are there lots of unrelated functions in a single module? It's ApplicationHelper
from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive
如果将模块上的方法转换为模块函数,则可以简单地从Mods调用它,就好像它已被声明为
If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as
module Mods
def self.foo
puts "Mods.foo(self)"
end
end
下面的module_function方法将避免破坏包含所有Mod的任何类.
The module_function approach below will avoid breaking any classes which include all of Mods.
module Mods
def foo
puts "Mods.foo"
end
end
class Includer
include Mods
end
Includer.new.foo
Mods.module_eval do
module_function(:foo)
public :foo
end
Includer.new.foo # this would break without public :foo above
class Thing
def bar
Mods.foo
end
end
Thing.new.bar
但是,我很好奇为什么首先将一组不相关的功能全部包含在同一个模块中?
However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?
已编辑,以显示如果在module_function :foo