我有一个模块,想混合一些方法作为类方法,一些方法作为实例方法。
例如:
module Foo
def self.class_method
end
def instance_method
end
end
class Bar
include Foo
end
用法:
Bar.class_method
Bar.new.instance_method
在 Ruby 中可以这样做吗?
如果不是,是否可以在 Bar 类中定义哪些方法是类方法,哪些是实例方法?
我不希望将同一个方法同时定义为类方法和实例方法。
最佳答案
这种模式在 Ruby 中很常见。如此普遍,事实上,ActiveSupport::Concern对其进行了一些抽象。
您的典型实现如下所示:
module Foo
def self.included(other_mod)
other_mod.extend ClassMethods
end
def instance_method
end
module ClassMethods
def class_method
end
end
end
class Bar
include Foo
end
不幸的是,如果不以某种方式将包含的模块分成多个部分,您将无法像您描述的那样轻松完成此操作。
关于ruby - 如何从 Ruby 中的模块中混合一些类方法和一些实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21918056/