[英]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.