分类方法通常用self.foo
或class << self
来定义。是否有可能创建一个模块或父类,使Ruby中的所有方法类方法?
是否有可能通过使用模块或父类来创建所有方法的类方法?
例如:
class Foo
include ClassMethods
def bar
或
class Foo < ClassMethods
def bar
并使用
Foo.bar
会ClassMethods是什么呢?
分类方法通常用self.foo
或class << self
来定义。是否有可能创建一个模块或父类,使Ruby中的所有方法类方法?
是否有可能通过使用模块或父类来创建所有方法的类方法?
例如:
class Foo
include ClassMethods
def bar
或
class Foo < ClassMethods
def bar
并使用
Foo.bar
会ClassMethods是什么呢?
如果您可以负担得起Foo
是模块而不是类,请使用module_function
。
module Foo
module_function
def bar
那么这将工作:
Foo.bar
转换您Class
为Module
,并使用extend self
应该做你想要什么。对于模块中的每个方法,它都会创建一个类方法。
所以,你的例子可以写成:
module Foo
extend self
def bar
另一种方法是使用Module#refine,它可以把一个类到一个模块。所以你可以创建你的类的一个模块,然后用你创建的模块扩展你的类。
根据Ruby风格指南(不是权威性指南,只是社区创建的建议指南),您应该将'module_function'放在'extend self'上:https://github.com/bbatsov/ruby-style-guide #模块功能 – 2014-09-28 02:01:39