开发者

Does this rails code belong in Application Controller?

开发者 https://www.devze.com 2023-03-22 18:47 出处:网络
I have some code (that is working), but I just want to make sure I am putting it in the right place per rails conventions/best practices. The purpose of the code, is to generate a set of subheading na

I have some code (that is working), but I just want to make sure I am putting it in the right place per rails conventions/best practices. The purpose of the code, is to generate a set of subheading navigation links if '@facility' is defined (which could be done in one of several controllers). Right now, I have the following bits of code spread out as identified below.

My issue: this doesn't feel right, particularly the bit of logic at the beginning of the html template. I will also want to define a few other similar helpers to define these subhead links based on different models. Should this logic (of setting @subhead_links) be in the application controller? As a metho开发者_运维技巧d in each model (so I would set @subhead_links = @facility.subhead_links)?

I've looked some for answers, but this type of philosophical question isn't as readily google-able as an error code.

in application helper

  # build subhead
  def subhead_links(facility)
      links = [
          { :label => "Configure Facility", :path => facility_path(facility) },
          { :label => "Waitlists", :path => waitlist_tiers_path(:id => facility.id) },
          { :label => "Applications", :path => sponsors_path(:id => facility.id) }
      return links
  end

in a partial included in application.html.erb template

<% if @facility %>
  <% @subhead_links = subhead_links(@facility) %>
<% end %>

<% if @subhead_links %>
  <nav class="subnav">
    <ul>
    <% @subhead_links.each do |link| %>
      <li><%= link_to link[:label], link[:path] %></li>
    <% end %>
    </ul>
  </nav>
<% end %>

in various other controllers...

@facility = Facility.find(params[:id])


I never rely on instance variables in partials and try to put as much logic as possible in helpers.

Here this would result in the following:

application_layout:

<%= render_subhead_links(@facility) %>

application_helper:

def render_subhead_links(facility)
  if facility
    links = [
      { :label => "Configure Facility", :path => facility_path(facility) },
      { :label => "Waitlists", :path => waitlist_tiers_path(:id => facility.id) },
      { :label => "Applications", :path => sponsors_path(:id => facility.id) }
    render :partial_name, :links => links
  end
end

partial:

<nav class="subnav">
  <ul>
    <% links.each do |link| %>
      <li><%= link_to link[:label], link[:path] %></li>
    <% end %>
  </ul>
</nav>
0

精彩评论

暂无评论...
验证码 换一张
取 消