Module: Kitestrings::Menu::ViewHelper

Defined in:
lib/kitestrings/menu/view_helper.rb

Instance Method Summary collapse

Instance Method Details

Generate a <li><a href=“path”>name</li> html string.

This is done from a Menu::Item object that fetches the path and display name from a resource(model, or any object with Menu::Model included in it.), or an array that would be passed to polymorphic_path

All other options are passed to link_to

Examples:

menu_link_to(current_menu_item)
menu_link_to(current_menu_item.sub_item(OtherModel)) # link to nested index page of OtherModel under current path
menu_link_to(:name => "Explicit", :path => path_method()) # specify name and path explicitly
menu_link_to("Explicit", :path => path_method()) # specify name and path explicitly
menu_link_to(@resource) # will link to resource_path(@resource)
menu_link_to([@user, @mail]) # will link to user_mail_path(@user, @mail)
menu_link_to([@user, Message]) # will link to user_messages_path(@user)
menu_link_to(@user, :id => :user_link, :class => "me") # pass options to link_to


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/kitestrings/menu/view_helper.rb', line 21

def menu_link_to(item, options={})
  case
    when item.is_a?(Hash)
      # for use like:   menu_item(name: "Selections", path: selections_path())
      options = item
      item = Menu::Item.new([])
    when item.is_a?(Array)
      item = Menu::Item.new(item)
    when item.is_a?(String)
      options[:name] = item
      item = Menu::Item.new([])
    when !item.is_a?(Menu::Item)
      item = Menu::Item.new([item])
  end

  # use explicitly given path, or calculate using polymorphic_path:
  path = options.delete(:path) ||
      begin
        if item.object.respond_to?(:new_record?) && item.object.new_record?
          polymorphic_path item.resources[0..-2] + [item.object.class]
        else
          item.path
        end
      rescue NoMethodError, ActionController::RoutingError
        Rails.logger.error("Menu item has no path: #{item.inspect}")
        nil
      end

  if path && !item.hidden?
    active = path == request.path # need to check request action perhaps? eg: GET, PUT, POST, etc.

    name = options.delete(:name) || item.name || ''

    # truncate long plain  strings with an elipsis
    if name.length > 30 && !name.html_safe?
      name = name[0..30] + ""
    end
    options[:id] ||= item.link_id
    li_class = active ? 'active' : ''

    # only generate the <li> tag if we have a name to display and a path to go to.
    if name.present?
      (:li, link_to(name, path, options), :class => li_class)
    end
  end
end