Class: Rack::Mount::RouteSet

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/mount/route_set.rb

Constant Summary collapse

X_CASCADE =
'X-Cascade'.freeze
PASS =
'pass'.freeze
PATH_INFO =
'PATH_INFO'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ RouteSet

Basic RouteSet initializer.

If a block is given, the set is yielded and finalized.

See other aspects for other valid options:

  • Generation::RouteSet.new

  • Recognition::RouteSet.new


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rack/mount/route_set.rb', line 21

def initialize(options = {}, &block)
  @parameters_key = options.delete(:parameters_key) || 'rack.routing_args'
  @parameters_key.freeze

  @named_routes = {}

  @recognition_key_analyzer = Analysis::Splitting.new

  @generation_keys = [:controller, :action]
  @generation_route_keys = []

  @request_class = options.delete(:request_class) || Rack::Request
  @valid_conditions = @request_class.public_instance_methods.map! { |m| m.to_sym }

  extend CodeGeneration unless options[:_optimize] == false
  @optimized_recognize_defined = false

  @routes = []
  expire!

  if block_given?
    yield self
    rehash
  end
end

Class Method Details

.new_without_optimizations(options = {}, &block) ⇒ Object

Initialize a new RouteSet without optimizations


10
11
12
# File 'lib/rack/mount/route_set.rb', line 10

def self.new_without_optimizations(options = {}, &block)
  new(options.merge(:_optimize => false), &block)
end

Instance Method Details

#add_route(app, conditions = {}, defaults = {}, name = nil) ⇒ Object

Builder method to add a route to the set

app

A valid Rack app to call if the conditions are met.

conditions

A hash of conditions to match against. Conditions may be expressed as strings or regexps to match against.

defaults

A hash of values that always gets merged in

name

Symbol identifier for the route used with named route generations


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rack/mount/route_set.rb', line 56

def add_route(app, conditions = {}, defaults = {}, name = nil)
  unless conditions.is_a?(Hash)
    raise ArgumentError, 'conditions must be a Hash'
  end

  unless conditions.all? { |method, pattern|
      @valid_conditions.include?(method)
    }
    raise ArgumentError, 'conditions may only include ' +
      @valid_conditions.inspect
  end

  route = Route.new(app, conditions, defaults, name)
  @routes << route

  @recognition_key_analyzer << route.conditions

  @named_routes[route.name] = route if route.name
  @generation_route_keys << route.generation_keys

  expire!
  route
end

#call(env) ⇒ Object

Rack compatible recognition and dispatching method. Routes are tried until one returns a non-catch status code. If no routes match, then catch status code is returned.

This method can only be invoked after the RouteSet has been finalized.


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/rack/mount/route_set.rb', line 134

def call(env)
  raise 'route set not finalized' unless @recognition_graph

  env[PATH_INFO] = Utils.normalize_path(env[PATH_INFO])

  request = nil
  req = @request_class.new(env)
  recognize(req) do |route, matches, params|
    # TODO: We only want to unescape params from uri related methods
    params.each { |k, v| params[k] = Utils.unescape_uri(v) if v.is_a?(String) }

    if route.prefix?
      env[Prefix::KEY] = matches[:path_info].to_s
    end

    old_params = env[@parameters_key]
    env[@parameters_key] = (old_params || {}).merge(params)

    result = route.app.call(env)

    if result[1][X_CASCADE] == PASS
      env[@parameters_key] = old_params
    else
      return result
    end
  end

  request || [404, {'Content-Type' => 'text/html', 'X-Cascade' => 'pass'}, ['Not Found']]
end

#freezeObject

Finalizes the set and builds optimized data structures. You must freeze the set before you can use call and url. So remember to call freeze after you are done adding routes.


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/rack/mount/route_set.rb', line 269

def freeze
  unless frozen?
    rehash
    stubbed_request_class

    @recognition_key_analyzer = nil
    @generation_route_keys    = nil
    @valid_conditions         = nil

    @routes.each { |route| route.freeze }
    @routes.freeze
  end

  super
end

#generate(method, *args) ⇒ Object

:nodoc:


216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/rack/mount/route_set.rb', line 216

def generate(method, *args) #:nodoc:
  raise 'route set not finalized' unless @generation_graph

  method = nil if method == :all
  named_route, params, recall, options = extract_params!(*args)
  merged = recall.merge(params)
  route = nil

  if named_route
    if route = @named_routes[named_route.to_sym]
      recall = route.defaults.merge(recall)
      url = route.generate(method, params, recall, options)
      [url, params]
    else
      raise RoutingError, "#{named_route} failed to generate from #{params.inspect}"
    end
  else
    keys = @generation_keys.map { |key|
      if k = merged[key]
        k.to_s
      else
        nil
      end
    }
    @generation_graph[*keys].each do |r|
      next unless r.significant_params?
      if url = r.generate(method, params, recall, options)
        return [url, params]
      end
    end

    raise RoutingError, "No route matches #{params.inspect}"
  end
end

#lengthObject

Number of routes in the set


252
253
254
# File 'lib/rack/mount/route_set.rb', line 252

def length
  @routes.length
end

#recognize(obj) ⇒ Object


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/rack/mount/route_set.rb', line 80

def recognize(obj)
  raise 'route set not finalized' unless @recognition_graph

  cache = {}
  keys = @recognition_keys.map { |key|
    if key.respond_to?(:call)
      key.call(cache, obj)
    else
      obj.send(key)
    end
  }

  @recognition_graph[*keys].each do |route|
    matches = {}
    params  = route.defaults.dup

    if route.conditions.all? { |method, condition|
        value = obj.send(method)
        if condition.is_a?(Regexp) && (m = value.match(condition))
          matches[method] = m
          captures = m.captures
          route.named_captures[method].each do |k, i|
            if v = captures[i]
              params[k] = v
            end
          end
          true
        elsif value == condition
          true
        else
          false
        end
      }
      if block_given?
        yield route, matches, params
      else
        return route, matches, params
      end
    end
  end

  nil
end

#rehashObject

:nodoc:


256
257
258
259
260
261
262
263
264
# File 'lib/rack/mount/route_set.rb', line 256

def rehash #:nodoc:
  Utils.debug "rehashing"

  @recognition_keys  = build_recognition_keys
  @recognition_graph = build_recognition_graph
  @generation_graph  = build_generation_graph

  self
end

#url(env, *args) ⇒ Object

Generates a url from Rack env and identifiers or significant keys.

To generate a url by named route, pass the name in as a Symbol.

url(env, :dashboard) # => "/dashboard"

Additional parameters can be passed in as a hash

url(env, :people, :id => "1") # => "/people/1"

If no named route is given, it will fall back to a slower generation search.

url(env, :controller => "people", :action => "show", :id => "1")
  # => "/people/1"

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/rack/mount/route_set.rb', line 176

def url(env, *args)
  named_route, params = nil, {}

  case args.length
  when 2
    named_route, params = args[0], args[1].dup
  when 1
    if args[0].is_a?(Hash)
      params = args[0].dup
    else
      named_route = args[0]
    end
  else
    raise ArgumentError
  end

  only_path = params.delete(:only_path)
  recall = env[@parameters_key] || {}

  unless result = generate(:all, named_route, params, recall,
      :parameterize => lambda { |name, param| Utils.escape_uri(param) })
    return
  end

  parts, params = result
  return unless parts

  params.each do |k, v|
    if v
      params[k] = v
    else
      params.delete(k)
    end
  end

  req = stubbed_request_class.new(env)
  req._stubbed_values = parts.merge(:query_string => Utils.build_nested_query(params))
  only_path ? req.fullpath : req.url
end