class SensibleRoute

Representation of a single route. Readers: @path: the normalized, parameterized path for the route (i.e. /labels/12/edit) @url_details: controller and action, plus any non-default parameter formats as regexes @parameters: an array of parameter names @verb: HTTP verb (GET, POST, etc) @request_line: minus the protocol, the HTTP request line (i.e. GET /labels/12/edit).

Attributes

parameters[R]
path[R]
request_line[R]
url_details[R]
verb[R]

Public Class Methods

hook_rails() click to toggle source

For use in gem initialization - call this once Rails is fully loaded so that Rails.sensible_routes can be set up.

# File lib/sensible_routes.rb, line 57
  def self.hook_rails
    Rails.instance_eval <<EOF
      cache.delete :sensible_routes
    
      def self.sensible_routes
        Rails.cache.fetch :sensible_routes do
          routes = SensibleRouteCollection.new
          Rails.application.routes.routes.to_a.each { |r| routes.add(SensibleRoute.new(r)) }
          return routes
        end
      end
EOF
  end
new(rt) click to toggle source

Initialize a new SensibleRoute. @param rt a Journey route, as used internally by Rails

# File lib/sensible_routes.rb, line 14
def initialize(rt)
  @parameters = []

  formatter = rt.path.build_formatter
  parts = []
  matcher = []

  # Yes, this is a hack. Yes, it will probably break. No, it's not 'temporary'.
  internal = formatter.instance_variable_get :@parts
  internal.each do |part|
    if part.is_a? String
      parts << part
      matcher << part
    elsif part.is_a? ActionDispatch::Journey::Format::Parameter
      parts << ":#{part.name}"
      @parameters << part.name
      matcher << if rt.requirements[part.name.to_sym]
                   rt.requirements[part.name.to_sym]
                 else
                   '[^/]+'
                 end
    elsif part.is_a? ActionDispatch::Journey::Format
      matcher << '(?:\.[^/]+)?'
    end
  end

  @path = parts.join
  @url_details = rt.requirements
  @verb = rt.verb
  @request_line = "#{@verb} #{@path}"
  @regex = Regexp.new "^#{matcher.join}$"
end

Public Instance Methods

match?(path) click to toggle source

Given a path (such as /labels/12/edit), detect whether that path is a match for this route (i.e. the route is actually /labels/:id/edit, but /labels/12/edit is a match for that). @param path the path string to test @return boolean

# File lib/sensible_routes.rb, line 51
def match?(path)
  @regex.match?(path)
end