Class: Sidewalk::UriMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/sidewalk/uri_mapper.rb

Overview

Maps URIs to Controllers.

Used to decide how to respond to a given HTTP request.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri_map = {}) ⇒ UriMapper

Initialize a UriMapper.

This converts a convenient-to-write map into a fast-to-lookup map.

The input hash takes String regular expression patterns as keys, and values can either be another map, a Controller class (not an instance), a Symbol or String that is the name of a Controller class, or a Proc.

If the value is a String, it will:

  • see if a Class with the same name exists; if so, use that.

  • try to require foo_bar_controller.rb for ‘FooBarController’

  • see if a Class now exists with the same name

  • if so, done; if not, bail out.

It looks for controller files in Application.local_root/controllers

You usually won’t interact with this class directly - instead you’ll usually pass the input hash to Application.

Keys are required to be Strings instead of Regexps because they are converted to a Sidewalk::Regexp behind the scenes; this is is the same thing as a ::Regexp on Ruby 1.9, but on Ruby 1.8 it adds several additional features such as named captures.

Examples:

A Simple Map

urimap = {
  '$' => :IndexController,
  'hello$' => :HelloController,
}
run Sidewalk::Application.new(urimap)

A Nested Map

urimap = {
  '$' => :IndexController,
  'foo/' => {
    '$' => :FooController,
    'bar$' => :FooBarController,
  },
}
run Sidewalk::Application.new(urimap)

A Map With Named Captures

urimap = {
  '$' => :IndexController,
  'foo/$' => :FooController,
  '~(?<username>[^/]+)/$' => :UserController
}
run Sidewalk::Application.new(urimap)

Parameters:

  • uri_map (Hash) (defaults to: {})


65
66
67
68
69
70
71
72
73
74
75
# File 'lib/sidewalk/uri_mapper.rb', line 65

def initialize uri_map = {}
  unless uri_map.is_a? Hash
    raise ArgumentError.new('URI map must be a Hash')
  end
  $LOAD_PATH.push File.join(
    Sidewalk::Application.local_root,
    'controllers'
  )
  @uri_map = Sidewalk::UriMapper.convert_map(uri_map)
  $LOAD_PATH.pop
end

Instance Attribute Details

#uri_mapHash<Regexp,(Controller|Proc)> (readonly)

The normalized URI map.

Returns:



92
93
94
# File 'lib/sidewalk/uri_mapper.rb', line 92

def uri_map
  @uri_map
end

Instance Method Details

#map(path) ⇒ UriMatch?

Given a path, find what should respond to it.

Returns:

  • (UriMatch)

    if something was found.

  • (nil)

    if there is no match.



81
82
83
84
85
86
87
# File 'lib/sidewalk/uri_mapper.rb', line 81

def map path
  Sidewalk::UriMapper.map(
    [], #stack
    self.uri_map,
    path
  )
end