Class: Rage::Router::Backend

Inherits:
Object
  • Object
show all
Defined in:
lib/rage/router/backend.rb

Constant Summary collapse

OPTIONAL_PARAM_REGEXP =
/\/?\(\/?(:\w+)\/?\)/
STRING_HANDLER_REGEXP =
/^([a-z0-9_\/]+)#([a-z_]+)$/

Instance Method Summary collapse

Constructor Details

#initializeBackend

Returns a new instance of Backend.



9
10
11
12
13
# File 'lib/rage/router/backend.rb', line 9

def initialize
  @routes = []
  @trees = {}
  @constrainer = Rage::Router::Constrainer.new({})
end

Instance Method Details

#lookup(env) ⇒ Object



48
49
50
51
# File 'lib/rage/router/backend.rb', line 48

def lookup(env)
  constraints = @constrainer.derive_constraints(env)
  find(env, constraints)
end

#on(method, path, handler, constraints: {}) ⇒ Object



15
16
17
18
19
20
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
46
# File 'lib/rage/router/backend.rb', line 15

def on(method, path, handler, constraints: {})
  raise "Path could not be empty" if path&.empty?

  if match_index = (path =~ OPTIONAL_PARAM_REGEXP)
    raise "Optional Parameter has to be the last parameter of the path" if path.length != match_index + $&.length

    path_full = path.sub(OPTIONAL_PARAM_REGEXP, "/#{$1}")
    path_optional = path.sub(OPTIONAL_PARAM_REGEXP, "")

    on(method, path_full, handler, constraints: constraints)
    on(method, path_optional, handler, constraints: constraints)
    return
  end

  if handler.is_a?(String)
    raise "Invalid route handler format, expected to match the 'controller#action' pattern" unless handler =~ STRING_HANDLER_REGEXP

    controller, action = to_controller_class($1), $2
    run_action_method_name = controller.__register_action(action.to_sym)

    handler = eval("->(env, params) { #{controller}.new(env, params).#{run_action_method_name} }")
  else
    raise "Non-string route handler should respond to `call`" unless handler.respond_to?(:call)
    # while regular handlers are expected to be called with the `env` and `params` objects,
    # lambda handlers expect just `env` as an argument;
    # TODO: come up with something nicer?
    orig_handler = handler
    handler = ->(env, _params) { orig_handler.call(env) }
  end

  __on(method, path, handler, constraints)
end