自定义 Rails *_for 助手?



我发现自己在显示视图中使用 Rails 的form_for来利用 AR 对象的翻译和其他方法来创建非交互式表单来显示对象。不过,必须有更好的方法来使用自定义构建器来做到这一点。有没有任何东西(宝石或 diy 教程方面(用于这种功能?我的搜索技能很差。

例如,如果我能写这样的东西,那就太好了:

<%= dl_for(@cog) do |dl| %>
<%= dl.dt_dd(:name) %>
<%= dl.dt_dd(:colors) { |colors| colors.to_sentence } %>
<%= dl.dt_dd(:size, { class: @cog.size }) %>
<% end %>

并获得:

<dl>
<dt>My Name Translation</dt>
<dd>Cog 1</dd>
<dt>My Colors Translation</dt>
<dd>Red, Green and Blue</dd>
<dt class="Small">My Size Translation</dt>
<dd class="Small">Small</dd>
</dl>

您可以使用表示器模式的变体来创建自己的元素生成器:

class DefinitionListBuilder
attr_reader :object
# context is the view context that we can call the rails helper
# method on
def initialize(object, context, **options)
@object = object
@context = context
@options = options
@i18n_key = object.model_name.i18n_key
end
def h
@context
end
def dl(&block)
@context.content_tag :dl, @options do
yield self
end
end
def dt_dd(attribute, **options)
h.capture do
h.concat(h.content_tag :dt, translate_attribute(attribute), options)
h.concat(h.content_tag :dd, object.send(attribute), options)
end
end
private
def translate_attribute(attribute)
key = "activerecord.attributes.#{@i18n_key}.#{attribute}"
h.t(key)
end
end

这个普通的旧红宝石对象相当于一个FormBuilder。它实际上只是一个包装模型实例并提供作用域为该实例的帮助程序的对象。然后,创建一个帮助程序,用于创建元素生成器的实例:

module DefinitionListHelper
def dl_for(record, **options, &block)
builder = DefinitionListBuilder.new(record, self, options)
builder.dl(&block)
end
end

这相当于提供form_forActionView::Helpers::FormHelper

为了简洁起见,这被简化了,#dd_dt不会阻塞。

例:

# config/locales/se.yml
se:
activerecord:
attributes:
cog:
name: 'Namn'
size: 'Storlek'
color: 'Färg'
<%= dl_for(Cog.new(name: 'Cogsworth', size: 'biggish', color: 'red')) do |builder| %>
<%= builder.dt_dd :name %>
<%= builder.dt_dd :size %>
<%= builder.dt_dd :color %>
<% end %>

网页输出:

<dl>
<dt>Namn</dt><dd>Cogsworth</dd>
<dt>Storlek</dt><dd>biggish</dd>
<dt>Färg</dt><dd>red</dd>
</dl>

最新更新