Ruby on rails Ruby如何将命名空间的模块函数委托给Namespace::Base内部类
我面临着选择#1: 然而,我觉得调用Ruby on rails Ruby如何将命名空间的模块函数委托给Namespace::Base内部类,ruby-on-rails,ruby,ruby-on-rails-5,ruby-2.3.1,Ruby On Rails,Ruby,Ruby On Rails 5,Ruby 2.3.1,我面临着选择#1: 然而,我觉得调用Abstract::Base.some_class_method有点奇怪。是否可以添加模块功能委派?例如,如果我的Base是ActiveRecord或Mongoid模型(因此Foo和Bar类似于STI),我希望能够使用 Abstract.where(…)而不是Abstract::Base.where(…) 是否可以将模块功能。其中委托给常量/类基 差不多 module Abstract class Base end delegate_module
Abstract::Base.some_class_method
有点奇怪。是否可以添加模块功能委派?例如,如果我的Base
是ActiveRecord或Mongoid模型(因此Foo和Bar类似于STI),我希望能够使用
Abstract.where(…)
而不是Abstract::Base.where(…)
是否可以将模块功能。其中
委托给常量/类基
差不多
module Abstract
class Base
end
delegate_module_function :where, to: :Base
end
或者有其他更好的方法吗?您可以使用名为的标准Ruby库 对于多种方法,您可以编写:
delegate [:where, :another_method] => Base
这模块和类与任何其他对象一样都是对象,它们没有什么特别之处。在它们之间委派方法的方式与在任何其他两个对象之间委派方法的方式完全相同,因为它们只是任何其他对象。
module Abstract # Instead of class if I had used option #1
class SomeAbstractService
end
end
module Abstract
class Base
end
delegate_module_function :where, to: :Base
end
require 'forwardable'
module Abstract
extend SingleForwardable
class Base
def self.where(p)
"where from base : #{p}"
end
end
delegate :where => Base
end
Abstract.where(id: 3)
# => "where from base : {:id=>3}"
delegate [:where, :another_method] => Base