patternrubyrailsMinor
DRY up Rails Navigation Code
Viewed 0 times
coderailsnavigationdry
Problem
In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i would have to go through every view and add that link. I decide to make a partial view in layouts/_nav.haml which contains:
and then in my application_helper.rb i added:
I know this isn't the best approach, is there any way to DRY up this solution or make it better. Im using bootstrap and i tried the simple-navigation gem but it wasn't that useful in my situation.
= link_to 'Home', root_path, :class => "btn #{active_page(root_path)}"
= link_to 'Sign in', sign_in_path, :class => "btn #{active_page(sign_in_path)}"
= link_to 'Account', account_path, :class => "btn #{active_page(account_path)}"and then in my application_helper.rb i added:
def active_page(path)
'active' if current_page?(path)
endI know this isn't the best approach, is there any way to DRY up this solution or make it better. Im using bootstrap and i tried the simple-navigation gem but it wasn't that useful in my situation.
Solution
You could create another helper to create your navigation links:
Then in your view:
def navigation_link_to(text, path)
link_to text, path, class: "btn #{active_page(path)}"
endThen in your view:
= navigation_link_to 'Home', root_path
= navigation_link_to 'Sign in', sign_in_path
= navigation_link_to 'Account', account_pathCode Snippets
def navigation_link_to(text, path)
link_to text, path, class: "btn #{active_page(path)}"
end= navigation_link_to 'Home', root_path
= navigation_link_to 'Sign in', sign_in_path
= navigation_link_to 'Account', account_pathContext
StackExchange Code Review Q#26612, answer score: 7
Revisions (0)
No revisions yet.