我有一个 Rails 应用程序,它通过包装器反复与另一个 Web 服务器对话,我想将包装器放在单例类中,这样它就不会为每个请求都重新创建。很简单,我想:
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 将“设置 URL”与“初始化”分开似乎不是最佳选择。
最佳答案
将参数传递给单例
class Parameterized_Singleton
def initialize(a)
@pdf = a
puts @pdf
end
def self.instance(p)
begin
@@instance =Parameterized_Singleton.new(p)
private_class_method :new
rescue NoMethodError
# return @@instance # or you can return previous object
puts "Object Already Created"
exit
end
return @@instance
end
def scanwith(b)
puts "scan"
end
def show_frequence_distribution
puts "fd"
end
def show_object_number(a)
puts "no"
end
end
Parameterized_Singleton.instance(20).show_object_number(10)
Parameterized_Singleton.instance(10).show_object_number(20)
关于ruby-on-rails - ruby rails : Passing argument to singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1858109/