在视图中使用关注点

加文·贝尔森

我很担心

app / models / concerns / map_scope.rb

module MapScope
  extend ActiveSupport::Concern

  included do

    def map_scope(string_to_map)
      #some mapping logic happens here
      return string_to_map
    end

  end
end

app / views / customers / index.html.erb

          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Scope</th>
              </tr>
            </thead>

            <tbody>
              <% @customers.each do |customer| %>
                <tr>
                  <td><%= customer.id %></td>
                  <td>
                    <%= map_scope(customer.scope_name) %>
                  </td>

                </tr>
              <% end %>
            </tbody>
          </table>

我无法使下面的行起作用,因为我需要映射表中的每一行

<%= map_scope(customer.scope_name) %>

出现以下错误: undefined method map_scope' for #<#< Class..

如何在不使用应用程序控制器的情况下使map_scope函数可用于视图中?

Sebastian Palma的图片

如果您想在显示属性之前做任何事情,那么可以继续使用模型关注点,但是在访问该方法时:

# model
class Customer
  include MapScope
end

# model/concern
module MapScope
  extend ActiveSupport::Concern

  included do
    def map_scope
      foo
    end
  end
end

# view
<td>
  <%= customer.map_scope %> # foo
</td>

如果要使用帮助程序(在ApplicationHelper中):

# helpers/application_helper.rb
module ApplicationHelper
  def map_scope(string_to_map)
    foo
  end
end

# view
<td>
  <%= map_scope(customer.scope_name) %> # foo
</td>

如果要使用装饰器(drapergem/draper):

# app/decorators/customer_decorator.rb
class CustomerDecorator < Drapper::Decorator
  include Draper::LazyHelpers

  def map_scope
    # the customer object is "object" within the decorator classes.
    # object.scope_name 
    foo
  end
end

# view
<td>
  <%= customer.map_scope %> # foo
</td>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章