无法从RoR上的助手文件中定义的类中调用助手方法



我试图创建一个小助手方法,使我更容易在rails 上使用ui工具包创建表单

# app/helpers/form_helper.rb
module FormHelper
def styled_form_for(record)
form_for record do |form|
builder = StyledFormBuilder.new(form)
yield form, builder
end
end
class StyledFormBuilder
def initialize(form)
@form = form
@obj = form.object
end
def text_field(field, **props)
styled_field :field do
@form.text_field field, class: ['uk-input', @obj.errors[field].any? && 'uk-form-danger', *props.class],
**props
end
end
private
def styled_field(field)
errors = @form.object.errors[field].map do |error_message|
tag.span error_message, class: 'uk-text-danger'
end
tag.div class: 'uk-margin' do
"
#{@form.label(field, class: 'uk-form-label')}
#{yield}
#{errors.join(tag.br)}
".html_safe
end
end
end
end

但当我运行此程序时,我会得到错误NameError - undefined local variable or method 'tag' for #<FormHelper::StyledFormBuilder:0x00007ffa08141220>有没有一种方法可以在助手模块内创建一个类,并访问其他助手方法?如果没有,我该怎么做;正确的方式";?

您需要将视图上下文传递到类中:

# app/helpers/form_helper.rb
module FormHelper
def styled_form_for(record)
form_for record do |form|
builder = StyledFormBuilder.new(form, context: self)
yield form, builder
end
end
class StyledFormBuilder

def initialize(form, context:)
@form = form
@obj = form.object
@context = context
end
def text_field(field, **props)
styled_field :field do
@form.text_field field, class: ['uk-input', @obj.errors[field].any? && 'uk-form-danger', *props.class],
**props
end
end
private
def styled_field(field)
errors = @form.object.errors[field].map do |error_message|
@context.tag.span error_message, class: 'uk-text-danger'
end
@context.tag.div class: 'uk-margin' do
"
#{@form.label(field, class: 'uk-form-label')}
#{yield}
#{errors.join(tag.br)}
".html_safe
end
end
end
end

视图上下文是所有视图辅助对象和辅助对象混合在一起的上下文,也是渲染视图时的隐式自身。

相关内容

  • 没有找到相关文章

最新更新