Ruby on rails 一个自定义Rails*\u作为助手?
我发现自己在show视图中使用Rails的form_for来利用AR对象上的翻译和其他方法来创建非交互式表单来显示对象。不过,一定有更好的方法可以通过自定义生成器来实现这一点。对于这种功能,是否有任何关于gem或diy教程的建议?我的搜索技能不适合这个 例如,如果我能写这样的东西,那就太好了:Ruby on rails 一个自定义Rails*\u作为助手?,ruby-on-rails,actionview,Ruby On Rails,Actionview,我发现自己在show视图中使用Rails的form_for来利用AR对象上的翻译和其他方法来创建非交互式表单来显示对象。不过,一定有更好的方法可以通过自定义生成器来实现这一点。对于这种功能,是否有任何关于gem或diy教程的建议?我的搜索技能不适合这个 例如,如果我能写这样的东西,那就太好了: <%= dl_for(@cog) do |dl| %> <%= dl.dt_dd(:name) %> <%= dl.dt_dd(:colors) { |colors|
<%= 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>
您可以使用presenter模式的变体来创建自己的元素生成器:
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
这相当于ActionView::Helpers::FormHelper,它为提供表单
为了简洁起见,这是简化的,dd_dt不需要一个块
例如:
# config/locales/se.yml
se:
activerecord:
attributes:
cog:
name: 'Namn'
size: 'Storlek'
color: 'Färg'
HTML输出:
<dl>
<dt>Namn</dt><dd>Cogsworth</dd>
<dt>Storlek</dt><dd>biggish</dd>
<dt>Färg</dt><dd>red</dd>
</dl>
您需要的是自定义DSL领域特定语言。只要搜索ruby定制dsl,你会发现很多resurces,我不能特别推荐。谢谢max,这就足够了。
<dl>
<dt>Namn</dt><dd>Cogsworth</dd>
<dt>Storlek</dt><dd>biggish</dd>
<dt>Färg</dt><dd>red</dd>
</dl>