Class: Webmachine::Dispatcher::Route

Inherits:
Object
  • Object
show all
Includes:
Translation
Defined in:
lib/webmachine/dispatcher/route.rb

Overview

Pairs URIs with Resource classes in the Webmachine::Dispatcher. To create routes, use #add_route.

Constant Summary

MATCH_ALL =

When used in a path specification, will match all remaining segments

'*'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Translation

#t

Constructor Details

#initialize(path_spec, *guards, resource, bindings = {}) {|req| ... } ⇒ Route

Creates a new Route that will associate a pattern to a Resource.

Examples:

Standard route

Route.new(["*"], MyResource)

Guarded route

Route.new ["/notes"],
  ->(request) { request.method == "POST" },
  Resources::Note
Route.new ["/notes"], Resources::NoteList
Route.new ["/notes", :id], Resources::Note
Route.new ["/notes"], Resources::Note do |req|
  req.query['foo']
end

Yields:

  • (req)

    an optional guard block

Yield Parameters:

  • req (Request)

    the request object

Raises:

  • (ArgumentError)

See Also:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/webmachine/dispatcher/route.rb', line 57

def initialize(path_spec, *args)
  if args.last.is_a? Hash
    bindings = args.pop
  else
    bindings = {}
  end

  resource = args.pop
  guards = args
  guards << Proc.new if block_given?

  @path_spec = path_spec
  @guards    = guards
  @resource  = resource
  @bindings  =  bindings

  raise ArgumentError, t('not_resource_class', :class => resource.name) unless resource < Resource
end

Instance Attribute Details

#guardsArray<Proc> (readonly)



21
22
23
# File 'lib/webmachine/dispatcher/route.rb', line 21

def guards
  @guards
end

#path_specArray<String|Symbol> (readonly)



17
18
19
# File 'lib/webmachine/dispatcher/route.rb', line 17

def path_spec
  @path_spec
end

#resourceClass (readonly)



13
14
15
# File 'lib/webmachine/dispatcher/route.rb', line 13

def resource
  @resource
end

Instance Method Details

#apply(request) ⇒ Object

Decorates the request with information about the dispatch route, including path bindings.



87
88
89
90
91
92
93
# File 'lib/webmachine/dispatcher/route.rb', line 87

def apply(request)
  request.disp_path = request.uri.path.match(/^\/(.*)/)[1]
  request.path_info = @bindings.dup
  tokens = request.disp_path.split('/')
  depth, trailing = bind(tokens, request.path_info)
  request.path_tokens = trailing || []
end

#match?(request) ⇒ Boolean

Determines whether the given request matches this route and should be dispatched to the #resource.



79
80
81
82
# File 'lib/webmachine/dispatcher/route.rb', line 79

def match?(request)
  tokens = request.uri.path.match(/^\/(.*)/)[1].split('/')
  bind(tokens, {}) && guards.all? { |guard| guard.call(request) }
end