簡體   English   中英

在Ruby中的對象初始化器中捕獲塊

[英]Capture block in object initializer in Ruby

我的Rails應用程序中有一個Notification::Pseudo類,該類具有自定義的initialize方法。 我希望此方法捕獲傳遞給new的塊的輸出,並將其用作@message的值

class Notification::Pseudo
  attr_accessor :message
  def initialize(&block)
    @message = begin
      capture(&block) if block_given?
    end || ""
  end
end

在我看來,我有類似

- notification = Notification::Pseudo.new do
  This is a test!

但是,這不起作用。 這給了我錯誤ArgumentError: wrong number of arguments (0 for 1)

我的初始化器有什么問題?

您正在調用的capture方法是在內核模塊上定義的。 您要從ActionView::Helpers::CaptureHelper模塊調用capture 它自動包含在視圖上下文中,您需要在此上下文中運行它,因此需要:

class Notification::Pseudo
  attr_accessor :message
  def initialize(vc, &block)
    @message = begin
      vc.capture(&block) if block_given?
    end || ""
  end
end

#In your view

- notification = Notification::Pseudo.new self do
  This is a test!

更新:

要使其在視圖之外也可以工作,請執行以下操作:

class Notification::Pseudo
  attr_accessor :message
  def initialize(vc = nil, &block)
    @message = begin
      return unless block_given?
      vc ? vc.capture(&block) : block.call
    end || ""
  end
end

暫無
暫無

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

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