gpt4 book ai didi

ruby-on-rails-3 - 如何在助手的子类中捕获 block ?

转载 作者:行者123 更新时间:2023-12-03 14:57:50 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

module ApplicationHelper

class PModuleHelper
include ActionView::Helpers::TagHelper
def heading(head = "", &block)
content = block_given? ? capture(&block) : head.to_s
content_tag :h3, content, :class => :module_header
end
end

def getmh
PModuleHelper.new
end

end

给方法 heading 一个字符串(或符号) ,或块。

在 View 中:
<% mh = getmh %>
<%= mh.heading :bla %> // WORKS
<%= mh.heading do %> // FAILS
test 123
<% end %>

(注意 getmh 仅用于此示例, PModuleHelper 由我的应用程序中的某个其他进程返回,因此无需对此发表评论或建议将 heading 设为普通帮助方法,而不是类方法)

不幸的是,我总是收到以下错误:
wrong number of arguments (0 for 1)

capture(&block) 的行号称呼。

使用方法 capture在自己的助手类中?

最佳答案

我会做这样的事情:

module Applicationhelper
class PModuleHelper

attr_accessor :parent

def initialize(parent)
self.parent = parent
end

delegate :capture, :content_tag, :to => :parent

def heading(head = "", &block)
content = block_given? ? capture(&block) : head.to_s
content_tag :h3, content, :class => :module_header
end
end

def getmh
PModuleHelper.new(self)
end
end

我不能保证这会起作用,因为我有这个错误: undefined method 'output_buffer='而不是你提到的那个。我一直无法重现你的。

关于ruby-on-rails-3 - 如何在助手的子类中捕获 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7216148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com