How to Create a Rails View Helper Method
In this guide we're going to implement our tab functionality. If you have a look at our code, you'll see that our home tab will always be active since it's hard coded into the navigation partial. For obvious reasons this isn't a great strategy for our user interface. To fix this, let's create a Rails view helper method.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we're going to implement our tab functionality. If you have a look at our code, you'll see that our home tab will always be active since it's hard coded into the navigation partial. For obvious reasons this isn't a great strategy for our user interface. To fix this, let's create a Rails view helper method. Go to helpers folder and open the application_helper.rb.

# overtime-app/app/helpers/application_helper.rb

module ApplicationHelper
  def active?(path)
    "active" if current_page?(path)
  end
end

In this code, we are asking Ruby to make tabs active only when we are on the page associated with that tab.

Now we can call this method in the partial, like this:

<!-- overtime-app/app/views/shared/_nav.html.erb -->

<ul class="custom-nav nav nav-tabs">
  <li class="<%= active?(root_path) %>">
    <%= link_to "Home", root_path %>
  </li>
  <li class="<%= active?(posts_path) %>">
    <%= link_to "Time Entries", posts_path %>
  </li>
  <li class="dropdown pull-right">
    <a href="#" data-toggle="dropdown" class="dropdown-toggle">Account<strong class="caret"></strong></a>
    <ul class="dropdown-menu">
      <li>
        <%= link_to "Edit Details", edit_user_registration_path %>
      </li>
      <li class="divider">
      </li>
      <li>
        <%= link_to "Logout", destroy_user_session_path, method: :delete %>
      </li>
    </ul>
  </li>
</ul>

Next, start the rails server and open the browser. Navigate to Time Entries, and you'll see that the home tab is no longer active and the Time Entries tab is.

Here, we have followed Rails best practices, as we did not put the conditional logic in the view files, but instead created a rails helper method. This is how you should implement this type of dynamic behavior when you want to have conditionals or any other logic in any of the view pages.

Resources