Convert a partial to method/block for speed

后端 未结 6 571
暗喜
暗喜 2021-02-06 13:46

I have a loop that renders a partial

1000.times do |i|
  render partial: \'test\', locals: {i: i}
end

this is really slow, up to 0.1 ms for for

6条回答
  •  误落风尘
    2021-02-06 14:36

    You could add a helper method and use content_tag. This accomplishes your goal of having a method work as a partial.

    def my_partial(i)
      content_tag(:div, i, class: 'iterator')
    end
    

    Using helper methods with content_tag probably isn't a good solution if you have a lot of content in your partial, for readability's sake.

    An alternative recommendation: Instead of rendering the same partial multiple times within a loop, you could render a single partial that includes a loop. If you needed to reuse the partial for only one object, you could just pass the object as an array.

    Here's a more real-world example:

    # index.html.erb
    <%= render partial: 'dogs', locals: {dogs: @dogs} %>
    
    # show.html.erb
    <%= render partial: 'dogs', locals: {dogs: [@dog]} %>
    
    # _dogs.html.erb
    <% dogs.each do |dog| %>
      <%= dog.name %>
    <% end %>
    

提交回复
热议问题