【问题标题】:Does a Rails plugin exist to build a show page (like a formbuilder)是否存在用于构建显示页面的 Rails 插件(如表单构建器)
【发布时间】:2012-10-12 20:40:54
【问题描述】:

我正在寻找一个 Rails 插件,为 show.html.erb 页面提供构建器。

例如,使用 SimpleForm,new.html.erb 页面可能如下所示:

<%= simple_form_for(@user, :url => user_registration_path, :html => ... }) do |f| %>
  <%= f.input :email, :required => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>
  ...
<% end %>

但我找不到仅显示字段的等效项。

生成的show.html.erb 页面如下所示:

<p>
  <b>Email:</b>
  <%= @user.email %>
</p>
...

但我想要类似的东西:

<%= simple_display_for(@user, :html => ... }) do |d| %>
  <%= d.output :email %>
  <%= d.output :name %>
  ...
<% end %>

这种建设者存在吗?

谢谢

编辑:如果构建者使用 Twitter Bootstrap,那就更好了:)

【问题讨论】:

  • 查看Draper。它提供了一种将 Presenter 添加到您的应用程序的简单方法,您可以使用它来创建一些简单的辅助方法来获得您正在寻找的确切 DSL。

标签: ruby-on-rails-3


【解决方案1】:

我不知道有什么 gem,但这里有一个简单的示例,说明如何自己构建此功能,您可以对其进行扩展:

lib/simple_output.rb

class SimpleOutput
  def initialize(resource)
    @resource = resource
  end

  def output(attribute)
    @resource.send attribute
  end
end

config/initializers/simple_output.rb

require_dependency 'lib/simple_output'

helpers/simple_output_helper.rb

module SimpleOutputHelper
  def simple_output_for(resource, options={}, &block)
    content_tag :div, yield(SimpleOutput.new(resource)), options[:html] || {}
  end
end

users/show.html.erb

<%= simple_output_for(@user, html: { style: "background-color: #dedede" }) do |r| %>
  <%= r.output :name %>
  <%= r.output :email %>
<% end %>

现在,显然这只是一个非常简单的示例,但希望它能让您走上正确的道路。查看 simple_form 源代码,了解它们如何组织代码,以及它们如何“类型转换”字段。 simple_form 代码库非常干净且易于使用 Ruby,是 gem 应该是什么样子的一个很好的例子。

【讨论】:

  • 谢谢,这是一个非常有用的 sn-p ;不确定我是否必须接受它,因为这并没有真正回答我的问题......
  • 给男人一条鱼... ;) 别担心,我只是将它作为答案发布,因为它作为评论发布太长了。我认为我的评论(关于Draper)实际上更接近答案。
猜你喜欢
  • 1970-01-01
  • 2022-09-30
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多