我正在开发一个基于Rails(3.2.11版本)的应用程序,我使用了Ruby Library来实现单例模式的服务。我尝试着避免在每次需要使用它时都调用instance
方法(如SomethingService.instance.get(some_id)
),并通过以下方式解决了这个问题。
class SomethingService
include Singleton
class << self
extend Forwardable
def_delegators :instance, *ShoppingListService.instance_methods(false)
end
end
这个解决方案之前一直运行得很好,但是我有很多服务,我不想在所有类中都添加这段代码!相反,我试图将它放在一个超级类中,像这样:
class ServiceBase
include Singleton
def self.inherited(subclass)
super(subclass) # needed because inherited is override by Singleton
class << subclass
extend Forwardable
def_delegators :instance, *self.instance_methods(false)
end
end
end
不过这让我遇到了一个 堆栈溢出
错误,大佬们有什么想法吗?