Module: Sinatra::RoutingPlugin

Defined in:
lib/sinatra/routing_plugin.rb,
lib/sinatra/routing_plugin/named_route.rb,
lib/sinatra/routing_plugin/routing_helpers.rb

Defined Under Namespace

Modules: RoutingHelpers Classes: NamedRoute

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/sinatra/routing_plugin.rb', line 8

def self.registered(app)
  # Named paths stores the named route aliases mapping to the url
  # i.e { [:account] => '/account/path', [:admin, :show] => '/admin/show/:id' }
  app.set :named_paths, {}
  app.set :app_name, app.name.underscore.to_sym unless app.respond_to?(:app_name)
  app.set :uri_root, '/' unless app.respond_to?(:uri_root)
  app.helpers Sinatra::RoutingPlugin::RoutingHelpers
end

Instance Method Details

#map(*args, &block) ⇒ Object

map constructs a mapping between a named route and a specified alias the mapping url can contain url query parameters map(:accounts).to(‘/accounts/url’) map(:admin, :show).to(‘/admin/show/:id’) map(:admin) { |namespace| namespace.map(:show).to(‘/admin/show/:id’) }



22
23
24
25
# File 'lib/sinatra/routing_plugin.rb', line 22

def map(*args, &block)
  named_router = Sinatra::RoutingPlugin::NamedRoute.new(self, *args)
  block_given? ? block.call(named_router) : named_router
end

#namespace(name, &block) ⇒ Object

Used to define namespaced route configurations in order to group similar routes Class evals the routes but with the namespace assigned which will append to each route namespace(:admin) { get(:show) { “…” } }



30
31
32
33
34
# File 'lib/sinatra/routing_plugin.rb', line 30

def namespace(name, &block)
  original, @_namespace = @_namespace, name
  self.class_eval(&block)
  @_namespace = original
end

#route(verb, path, options = {}, &block) ⇒ Object

Hijacking route method in sinatra to replace a route alias (i.e :account) with the full url string mapping Supports namespaces by accessing the instance variable and appending this to the route alias name If the path is not a symbol, nothing is changed and the original route method is invoked



39
40
41
42
43
44
45
46
# File 'lib/sinatra/routing_plugin.rb', line 39

def route(verb, path, options={}, &block)
  if path.kind_of? Symbol
    route_name = [self.app_name, @_namespace, path].flatten.compact
    path = named_paths[route_name]
    raise RouteNotFound.new("Route alias #{route_name.inspect} is not mapped to a url") unless path
  end
  super verb, path, options, &block
end