6. REQUIREMENTS
We need to be able to check if we are rendering the destination of the
link and we then need to be able to set the class accordingly.
7. REQUIREMENTS
rake routes
Prefix Verb URI Pattern Controller#Action
portfolio GET /portfolio(.:format) welcome#portfolio
about GET /about(.:format) welcome#about
contact GET /contact(.:format) welcome#contact
shopify GET /shopify(.:format) welcome#shopify
root GET / welcome#home
link_to("About", about_path)
8. REQUIREMENTS
▸ need to determine current_path
▸ need to compare it to the link_path
▸ neet to set css_class_active_for(link_path)
<%= content_tag :li, link_to("About", about_path), class: "#{css_class_active_for(about_path)}" %>
12. TEST FOR current_path HELPER
application_helper_spec.rb
# 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 '#current_path' do
it "returns #request.env['PATH_INFO']" do
helper.request.env['PATH_INFO'] = '/welcome'
helper.current_path.should eq('/welcome')
end
end
end
13. CODE FOR current_path HELPER
application_helper.rb
module ApplicationHelper
def current_path
request.env['PATH_INFO']
end
end
14. TEST OF css_class_active_for
HELPER
layout_helper_spec.rb
require "spec_helper"
describe LayoutHelper do
context "#css_class_active_for" do
it "returns 'active' if the current path matches link path" do
helper.stub(:current_path).and_return('/about')
helper.stub(:about_path).and_return('/about')
expect(helper.css_class_active_for(about_path)).to match /active/
end
it "returns 'inactive' if the current path does not match the link path" do
helper.stub(:current_path).and_return('/')
helper.stub(:about_path).and_return('/about')
expect(helper.css_class_active_for(about_path)).to match /inactive/
end
end
end
15. require "spec_helper"
describe LayoutHelper do
context "#css_class_active_for" do
it "returns 'active' if the current path matches link path" do
helper.stub(:current_path).and_return('/about')
helper.stub(:about_path).and_return('/about')
expect(helper.css_class_active_for(about_path)).to match /active/
end
it "returns 'inactive' if the current path does not match the link path" do
helper.stub(:current_path).and_return('/')
helper.stub(:about_path).and_return('/about')
expect(helper.css_class_active_for(about_path)).to match /inactive/
end
end
end
16. CODE FOR css_class_active_for
HELPER
layout_helper.rb
module LayoutHelper
def css_class_active_for link_path
link_path == current_path ? "active" : "inactive"
end
end
17. THAT'S IT
Xander Miller
twitter: @pareidoliax
blog: http://pareidoliax.ca
github: pareidoiax