是否可以在 Ruby 中基于单例类定义一个新的非单例类?
我尝试了这样的事情(片段):
module SomeModule
extend self
class Singleton;end
end
class NonSingleton
include SomeModule
end
nonsingleton = NonSingleton.new
但是,当然对你们大师来说,这已经很明显了,这不会像我预期的那样起作用。
基本上我想要的是重用 Singleton 类的功能,而不以任何方式影响它的行为。可能吗?
经过进一步调查,这似乎根本不可能(如果我错了,请纠正我)。像跟随这样的黑客会太丑陋/凌乱吗?
singleton = File.read('some_singleton.rb')
non_singleton = eval(singleton.gsub('include Singleton', ''))
# Or perhaps:
non_singleton = eval(singleton.gsub('module SomeModule', 'module MyOwnModule'))