Sha256: a610975951930cd4a7f62fef50816e16bf42371af0b9bb699504000c42994af3

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

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
          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.routes
      @@routes ||= {}
    end

    def self.registered(app)
      app.helpers NamedRoutes::Helpers
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sinatra-named-routes-subdomains-0.1.5 lib/sinatra/named_routes.rb