|
module NavigationLinkHelper |
|
def navigation_link(title, path, html_options = {}, options = {}) |
|
NavigationLink.new(request, title, path, html_options, options).to_html |
|
end |
|
|
|
class NavigationLink |
|
include ActionView::Helpers::UrlHelper |
|
|
|
def initialize(request, title, path, html_options, options) |
|
@request = request |
|
@title = title |
|
@path = path |
|
@html_options = html_options |
|
@options = options |
|
end |
|
|
|
def to_html |
|
html = if @options[:wrapper] |
|
puts wrapper_classes.inspect |
|
content_tag(@options[:wrapper], link, :class => wrapper_classes) |
|
else |
|
link |
|
end |
|
|
|
html.html_safe |
|
end |
|
|
|
private |
|
|
|
def default_link_classes |
|
@html_options[:class].to_s.split(/\s+/) |
|
end |
|
|
|
def wrapper_classes |
|
classes = @options[:wrapper_class].to_s.split(/\s+/) |
|
classes.present? ? classes : nil |
|
end |
|
|
|
def controller_for(path) |
|
Rails.application.routes.recognize_path(path)[:controller] |
|
end |
|
|
|
def controller_segment |
|
@options[:controller_segment] || @options[:url_segment] |
|
end |
|
|
|
def compare_path |
|
compare_path = @request.fullpath |
|
compare_path.gsub!(/\?.*/, '') if @options[:ignore_params] |
|
compare_path |
|
end |
|
|
|
def current_path |
|
current_path = url_for(@path) |
|
current_path.gsub!(/\?.*/, '') if @options[:ignore_params] |
|
current_path |
|
end |
|
|
|
def paths_match? |
|
compare_path == current_path |
|
end |
|
|
|
def segments_match? |
|
path_segment.present? && path_segment == current_segment |
|
end |
|
|
|
def path_segment |
|
if @options[:controller_segment] |
|
path_controller = controller_for(path) |
|
path_controller.split('/')[controller_segment] |
|
elsif @options[:url_segment] |
|
compare_path.split('/')[controller_segment] |
|
end |
|
end |
|
|
|
def current_segment |
|
if @options[:controller_segment] |
|
current_controller = controller_for(@request.path) |
|
current_controller.split('/')[controller_segment] |
|
elsif @options[:url_segment] |
|
current_path.split('/')[controller_segment] |
|
end |
|
end |
|
|
|
def selected_class |
|
@options[:selected_class] || 'selected' |
|
end |
|
|
|
def link_classes |
|
additional_classes = selected? ? [selected_class] : [] |
|
classes = default_link_classes + additional_classes |
|
classes.present? ? classes : nil |
|
end |
|
|
|
def selected? |
|
paths_match? || segments_match? |
|
end |
|
|
|
def link_options |
|
@html_options.merge(:class => link_classes) |
|
end |
|
|
|
def link |
|
link_to(@title, @path, link_options) |
|
end |
|
end |
|
end |