LinkToActiveState

Build Status Gem Version

A simple gem to implement active states on links using the standard Rails link_to helper. This can be helpful in navigation lists or buttons to give them a class when the current URL matches a condition on the link helper.

Installation

Add this line to your application's Gemfile:

gem 'link_to_active_state'

Or install from the repository:

gem 'link_to_active_state', git: 'git://github.com/robotmay/link_to_active_state.git', tag: 'v1.0.5'

And then execute:

$ bundle

Or install it yourself as:

$ gem install link_to_active_state

Usage

This gem adds a small bit of extra functionality to the default Rails link_to view helper. It provides a very simple way of adding classes to links based on the current path.

Examples

Test the path using a string/path helper:

link_to "Account", , active_on: 

Which, if the request.fullpath matches account_path, will result in:

<a href="/account" class="active">Account</a>

Using a regular expression:

link_to "Account", , active_on: /\/account/i

Or a proc:

link_to "Account", , active_on: lambda { request.fullpath ==  }

Any other value will cause it to be matched against the URL supplied to the link_to helper:

link_to "Account", , active_on: true

Custom options

By default the class "active" will be added to the existing classes of the link. However you can specify your own:

link_to "Account", , active_on: /\/account/i, active_state: "highlighted"
<a href="/account" class="highlighted">Account</a>

You can also customise other options by using a proc:

link_to "Account", , active_on: /\/account/i, active_state: lambda { |html_options|
  html_options.merge({ "data-active" => "true" })
}
<a href="/account" data-active="true">Account</a>

Wrappers

If you need an active class on an li tag, for use in a Bootstrap nav for example:

link_to "Account", , active_on: , active_wrapper: :li

Which will result in:

<li class="active">
  <a href="/account" class="active">Account</a>
</li>

Note the li tag is included as part of the html generated by the link_to helper and should not be added separately.

You can also pass a proc to the wrapper option. This takes two arguments; the generated link and the options for the wrapper (which will include the active state class):

link_to "Account", , 
  active_on: ,
  active_wrapper: proc { |link, wrapper_opts|
    (:li, link, wrapper_opts)
  }

And for either of the above methods you can supply HTML attributes for the wrapper:

link_to "Account", ,
  active_on: ,
  active_wrapper: :li,
  active_wrapper_options: { rel: "gallery" }

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request