Ruby on Rails:将参数传递给单例
我有一个 Rails 应用程序,它通过包装器反复与另一个 Web 服务器通信,我想将包装器放在 Singleton 类中,这样就不会为每个请求重新创建它。很简单,我想:
class AppWrapper < Wrapper
include Singleton
end
...
wrapper = AppWrapper.instance "url"
只是它不起作用:
wrong number of arguments (0 for 1)
/usr/lib/ruby/1.8/singleton.rb:94:in `initialize'
/usr/lib/ruby/1.8/singleton.rb:94:in `new'
/usr/lib/ruby/1.8/singleton.rb:94:in `instance'
Wrapper.initialize 需要一个参数,并且显然它没有被传递,因为有问题的第 94 行说
@__instance__ = new # look Ma, no argument
我如何解决这个问题?在 AppWrapper 中重新定义初始化似乎没有帮助,并且 使用 Wrapper 将“set URL”与“initialize”分开似乎不是最理想的。
I have a Rails app that repeatedly talks to another Web server through a wrapper, and I'd like to stick the wrapper in a Singleton class so it's not recreated for every request. Easy enough, I thought:
class AppWrapper < Wrapper
include Singleton
end
...
wrapper = AppWrapper.instance "url"
Only it doesn't work:
wrong number of arguments (0 for 1)
/usr/lib/ruby/1.8/singleton.rb:94:in `initialize'
/usr/lib/ruby/1.8/singleton.rb:94:in `new'
/usr/lib/ruby/1.8/singleton.rb:94:in `instance'
Wrapper.initialize needs an argument, and apparently it's not getting passed through, since line 94 in question says
@__instance__ = new # look Ma, no argument
How do I work around this? Redefining initialize in AppWrapper doesn't seem to help, and
mucking around with Wrapper to separate "set URL" from "initialize" seems suboptimal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将参数传递给单例
Passing argument to singleton
你确定你需要一个单身人士而不是一个工厂吗?请参阅此
Are you sure you need a singleton and not a factory . Refer this
当我还在了解 Ruby 的时候我就问了这个问题,现在看来很天真。简单的解决方案是将 Wrapper 对象存储在成员变量中,并仅在尚未设置时使用
||=
对其进行初始化:I asked this question while I was still getting my head around Ruby, and it seems so naive now. The easy solution is to just store the Wrapper object in a member variable and use
||=
to initialize it only if it hasn't been set yet:既然您提到了编辑 Wrapper 作为解决方案,那么您不能直接使用 Wrapper 并执行此操作吗?
如果没有,您可以使用类似的方法,这将确保 AppWrapper.new 不会被多次调用:
如果您需要单例“Klass.instance”方法,则必须取出参数Wrapper#initialize,或者只是重新定义 Singleton#instance 以选择性地接受参数并将它们传递给第 94 行的 new 调用。
Since you mention something about editing Wrapper as a solution, can't you just use Wrapper directly and do this?
If not, you could use something like this, which will just make sure AppWrapper.new isn't called more than once:
If you need the singleton "Klass.instance" method, you'll have to take either take out the parameter in Wrapper#initialize, or just redefine Singleton#instance to take arguments optionally and passes them to the call to new on line 94.