require File.join(File.dirname(__FILE__), 'version') require File.join(File.dirname(__FILE__), 'route_parser') module Sinatra module NamedRoutes module Helpers # Generates the absolute URI for a given path in the app. # Takes Rack routers and reverse proxies into account. # Extended support passing in named route and parameters. def uri( addr = nil, absolute = true, params = nil ) if addr.is_a? Symbol if !params.nil? params = params.merge( NamedRoutes.get_params( addr ) ) else params = NamedRoutes.get_params( addr ) end addr = NamedRoutes.get_path( addr, params ) end return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ uri = [host = ""] if absolute host << "http#{'s' if request.secure?}://" if request.forwarded? or request.port != (request.secure? ? 443 : 80) domain = request.host_with_port else domain = request.host end if !params.nil? && !params[:subdomain].nil? host << domain.gsub(/^([a-zA-Z-]+)\./, "#{params[:subdomain]}.") else host << domain end end uri << (addr ? addr : request.path_info).to_s File.join uri end alias :to :uri alias :url :uri end # Maps a path to name. def map(name, path, params = {}) NamedRoutes.routes[name] = Route.new path, params end alias :bind :map private def route(verb, path, options={}, &block) if path.is_a?(Symbol) path = NamedRoutes.routes[path].source end super(verb, path, options, &block) end def self.get_path(name, params = {}) raise ArgumentError, "No route with the name #{name} exists." if NamedRoutes.routes.nil? NamedRoutes.routes[name].build params end def self.get_params(name) raise ArgumentError, "No route with the name #{name} exists." if NamedRoutes.routes.nil? NamedRoutes.routes[name].params end def self.routes @@routes ||= {} end def self.registered(app) app.helpers NamedRoutes::Helpers end end end