目前我有这样一个模块:
module MyModule
def A
end
.....
end
我有一个模型,我想将该方法 A 用作类方法。但是,问题是我只需要那个 A 方法。如果我扩展它,我会将其他不必要的类方法扩展到我的模型中。因此,有没有办法让我像 MyModule.A 那样做某事而无需像这样重写模块:
module MyModule
def A
...
end
def self.A
...
end
.....
end
如果我那样做,有点重复我自己。我仍然觉得在 Rails 中有更好的方法来做到这一点。
最佳答案
使用Module#module_function
使单个函数成为模块函数:
module M
def m1; puts "m1"; end
def m2; puts "m2"; end
module_function :m2
end
或:
module M
def m1; puts "m1"; end
module_function # from now on all functions are defined as module_functions
def m2; puts "m2"; end
end
M.m1 #⇒ NoMethodError: undefined method `m1' for M:Module
M.m2 #⇒ "m2"
关于ruby-on-rails - 有没有办法在模块中使用类方法而不在 Rails 中扩展它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293304/