簡體   English   中英

Ruby on Rails:將參數傳遞給singleton

[英]Ruby on Rails: Passing argument to singleton

我有一個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”分開似乎不是最理想的。

將論證傳遞給單身人士

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時,我問了這個問題,現在看起來很天真。 簡單的解決方案是將Wrapper對象存儲在成員變量中,並使用||=初始化它,只有尚未設置它:

class WrapperUserClass
  def initialize
     @wrapper = nil # Strictly speaking unnecessary, but it's a bit clearer this way
  end

  def wrapper
    @wrapper ||= Wrapper.new(foobar)
  end

  def do_something
    wrapper.booyakasha
  end
end

既然你提到有關編輯Wrapper作為解決方案的事情,你不能直接使用Wrapper並執行此操作嗎?

class Wrapper; include Singleton; end

如果沒有,你可以使用這樣的東西,這將確保不會多次調用AppWrapper.new:

class AppWrapper
  def self.new(*args)
    class << app_wrapper = Wrapper.new(*args)
      include Singleton
    end
    app_wrapper
  end
end

如果你需要單例“Klass.instance”方法,你必須取出Wrapper #initialize中的參數,或者只是重新定義Singleton#instance以選擇性地獲取參數並將它們傳遞給第94行的new調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM