Skip to content

Instantly share code, notes, and snippets.

@xander-miller
Last active August 29, 2015 14:05
Show Gist options
  • Save xander-miller/465d47634be0b4415dd7 to your computer and use it in GitHub Desktop.
Save xander-miller/465d47634be0b4415dd7 to your computer and use it in GitHub Desktop.
Making a Dynamic Navigation in your Rails 4 layout
<nav>
<ul class="nav nav-pills">
<%= content_tag :li, link_to("Portfolio", welcome_portfolio_path), class: display_active('welcome#portfolio') %>
<%= content_tag :li, link_to("About", welcome_about_path), class: display_active('welcome#about') %>
<%= content_tag :li, link_to("Contact", welcome_contact_path), class: display_active('welcome#contact') %>
</ul>
</nav>
module ApplicationHelper
def controller_action_name
"#{controller_name}##{action_name}"
end
def display_active controller_action
controller_action == controller_action_name ? "active" : ""
end
end
# helper is an instance of ActionView::Base configured with the
# ApplicationHelper and all of Rails' built-in helpers
require "spec_helper"
describe ApplicationHelper do
context '#controller_action_name' do
it "calls #action_name" do
helper.should_receive(:action_name)
helper.controller_action_name
end
it 'calls #controller_name' do
helper.should_receive(:controller_name)
helper.controller_action_name
end
it 'returns a concatination of #controller_name and #action_name' do
helper.stub(:controller_name).and_return('welcome')
helper.stub(:action_name).and_return('about')
helper.controller_action_name.should eq('welcome#about')
end
end
context "#display_active" do
it "returns 'active' if the current controller action equals the argument" do
helper.stub(:controller_action_name).and_return('welcome#about')
expect(helper.display_active('welcome#about')).to match /active/
end
it "returns '' if the current controller action does not equal the argument" do
helper.stub(:controller_action_name).and_return('welcome#about')
helper.display_active('welcome#contact').should eq('')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment