您可以使用演示者模式的变体来创建自己的元素构建器:
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
这个普通的旧 ruby 对象等同于 FormBuilder。这实际上只是一个包装模型实例并提供范围为该实例的帮助器的对象。然后,您创建一个帮助器来创建元素构建器的实例:
module DefinitionListHelper
def dl_for(record, **options, &block)
builder = DefinitionListBuilder.new(record, self, options)
builder.dl(&block)
end
end
这相当于提供form_for 的ActionView::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 %>
HTML 输出:
<dl>
<dt>Namn</dt><dd>Cogsworth</dd>
<dt>Storlek</dt><dd>biggish</dd>
<dt>Färg</dt><dd>red</dd>
</dl>