我定义了一个包含基本功能的方法的SomeClass
类。该类在Foo
模块中定义。
# foo/
# |--some_class.rb
module Foo
class SomeClass
def some_method
puts "Hi!"
end
end
end
我还有另外两个模块:Bar
和Baz
。我想在Foo
和Bar
中包含Baz
的整个命名空间,并继承Foo
下定义的所有方法,从而能够覆盖Foo
方法。
我还希望只能通过在右侧文件夹中指定一个新文件来覆盖此方法:
# baz/
# |--foo/
# |--some_class.rb
module Baz
module Foo
class SomeClass < ::Foo::SomeClass
def some_method
puts "Hey!"
end
end
end
end
这很好用。但是,我希望能够使用Bar::Foo::SomeClass.some_method
而无需创建 bar / foo / some_class.rb ,并定义空模块和空SomeClass。
这同样适用于模块的继承(通过包括)。
有没有办法通过使用include,extend或require或其他方法轻松完成此操作?由于这是Rails项目的一部分(在lib文件夹下),我可以以特定方式使用自动加载吗?
我想要实现这一点的原因是因为我在Foo
下有许多类和模块,其中包含类。 Bar
和Baz
模块应该能够继承Foo
下的所有模块/类,并通过创建显式文件覆盖需要它的实例或类方法。我想避免为Foo
和Bar
的每个类或模块Baz
创建一个文件。
到目前为止,我有以下解决方案。我定义了两个新文件: bar.rb 和 baz.rb 。在 bar.rb :
module Bar
def self.const_missing(name)
klass = Object.const_get(name.to_s) if name.to_s =~ /Foo/
return klass if klass
raise
rescue
super
end
end
> Bar
=> Bar # as expected
> Foo
=> Foo # as expected
> Bar::Foo
=> Foo # works!
> Bar::Foo::SomeClass
=> Foo::SomeClass # right
> Baz::Foo::SomeClass
=> Foo::SomeClass # not right...
我不确定我现在是否正在寻求一个好的解决方案。任何反馈都非常感谢。