Project

General

Profile

Download (1.95 KB) Statistics
| Branch: | Tag: | Revision:
611fd588 Amos Benari
module Menu
class Item < Node
attr_reader :name, :condition, :parent, :child_menus, :last, :html_options

def initialize(name, options)
raise ArgumentError, "Invalid option :if for menu item '#{name}'" if options[:if] && !options[:if].respond_to?(:call)
49a98083 Amos Benari
raise ArgumentError, "Invalid option :engine for menu item '#{name}'" if options[:engine] && !options[:engine].respond_to?(:routes)
611fd588 Amos Benari
raise ArgumentError, "Invalid option :html for menu item '#{name}'" if options[:html] && !options[:html].is_a?(Hash)
raise ArgumentError, "Cannot set the :parent to be the same as this item" if options[:parent] == name.to_sym
raise ArgumentError, "Invalid option :children for menu item '#{name}'" if options[:children] && !options[:children].respond_to?(:call)
@name = name
902c71ef Dmitri Dolguikh
@url = options[:url]
611fd588 Amos Benari
@url_hash = options[:url_hash]
@condition = options[:if]
@caption = options[:caption]
@html_options = options[:html] || {}
@parent = options[:parent]
@child_menus = options[:children]
@last = options[:last] || false
49a98083 Amos Benari
@context = options[:engine] || Rails.application
611fd588 Amos Benari
super @name.to_sym
end

49a98083 Amos Benari
def url
902c71ef Dmitri Dolguikh
add_relative_path(@url || @context.routes.url_for(url_hash.merge(:only_path=>true)))
49a98083 Amos Benari
end

611fd588 Amos Benari
def url_hash
49a98083 Amos Benari
@url_hash ||= @context.routes.url_helpers.send("hash_for_#{name}_path")
611fd588 Amos Benari
@url_hash.inject({}) do |h,(key,value)|
h[key] = (value.respond_to?(:call) ? value.call : value)
h
end
end

def authorized?
355bce36 Ohad Levy
User.current.allowed_to?(url_hash.slice(:controller, :action, :id))
43ebc4d4 Eric D. Helms
rescue => error
Rails.logger.error "#{error.message} (#{error.class})\n#{error.backtrace.join("\n")}"
a0e87b45 Ohad Levy
false
611fd588 Amos Benari
end

9b6e45e9 Lukas Zapletal
private

def add_relative_path(path)
rurl = @context.config.action_controller.relative_url_root
rurl.present? && !path.start_with?(rurl.end_with?('/') ? rurl : "#{rurl}/") ? "#{rurl}#{path}" : path
end
611fd588 Amos Benari
end
43ebc4d4 Eric D. Helms
end