3
\$\begingroup\$

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:

= 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)
end

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.

asked May 25, 2013 at 19:04
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

You could create another helper to create your navigation links:

def navigation_link_to(text, path)
 link_to text, path, class: "btn #{active_page(path)}"
end 

Then in your view:

= navigation_link_to 'Home', root_path
= navigation_link_to 'Sign in', sign_in_path
= navigation_link_to 'Account', account_path
answered May 25, 2013 at 19:46
\$\endgroup\$
7
  • \$\begingroup\$ +1 this is the bottom-up approach to DRY, let's hope someone to contribute the top-down approach :-) \$\endgroup\$ Commented May 25, 2013 at 20:04
  • \$\begingroup\$ What do you mean with "top-down DRY"? \$\endgroup\$ Commented May 25, 2013 at 20:12
  • \$\begingroup\$ A top-down DRYing here would use a each loop. \$\endgroup\$ Commented May 25, 2013 at 20:22
  • \$\begingroup\$ Ah yeah, I didn't wanna do that since I think this is more clear to read in the view code, than defining an array of objects. Perhaps unless you have a very large amount of links. \$\endgroup\$ Commented May 25, 2013 at 20:24
  • \$\begingroup\$ Exactly, when there are few elements that's the more readable. And when elements grow you can always combine both, a method abstraction + a loop of the data. \$\endgroup\$ Commented May 25, 2013 at 20:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.