Class: Mustermann::Router
- Inherits:
-
Object
- Object
- Mustermann::Router
- Defined in:
- lib/mustermann/router.rb
Overview
An extremely simple, Rack-compatible router implementation using Set for pattern matching.
Instance Method Summary collapse
-
#call(env) ⇒ Array
The Rack response array (status, headers, body).
- #fallback(fallback = nil, &block) ⇒ Object
-
#initialize(fallback = nil, key: "mustermann.match", **options, &block) ⇒ Router
constructor
Initializes a new router.
-
#path_for(app, behavior = nil, params = {}) ⇒ String
Helps generate links.
-
#route(verb, pattern, target = nil, **options) {|env| ... } ⇒ void
Adds a route for the given verb and pattern, with the given target.
Constructor Details
#initialize(fallback = nil, key: "mustermann.match", **options, &block) ⇒ Router
Initializes a new router.
49 50 51 52 53 54 55 56 57 58 |
# File 'lib/mustermann/router.rb', line 49 def initialize(fallback = nil, key: "mustermann.match", **, &block) @key = key @sets = VERBS.to_h { |verb| [verb, Set.new(**)] } @fallback = fallback || ->(env) { NOT_FOUND.dup } if block_given? instance_exec(&block) @sets.each_value(&:optimize!) end end |
Instance Method Details
#call(env) ⇒ Array
Returns The Rack response array (status, headers, body).
62 63 64 65 66 67 68 69 70 |
# File 'lib/mustermann/router.rb', line 62 def call(env) request_method = env["REQUEST_METHOD"] || "GET" request_method = "GET" if request_method == "HEAD" if routes = @sets[request_method] and match = routes.match(env["PATH_INFO"] || "/") env[@key] = match return match.value.call(env) end @fallback.call(env) end |
#fallback(fallback = nil, &block) ⇒ Object
72 |
# File 'lib/mustermann/router.rb', line 72 def fallback(fallback = nil, &block) = @fallback = fallback || block || @fallback |
#path_for(app, behavior = nil, params = {}) ⇒ String
Helps generate links
95 96 97 98 |
# File 'lib/mustermann/router.rb', line 95 def path_for(app, behavior = nil, params = {}) set = @sets.values.find { |s| s.has_value?(app) } || @sets[VERBS.first] set.(app, behavior, params) end |
#route(verb, pattern, target = nil, **options) {|env| ... } ⇒ void
Note:
Shorthand methods, like ‘get`, `post`, etc. dynamically are defined for all supported verbs.
This method returns an undefined value.
Adds a route for the given verb and pattern, with the given target.
84 85 86 87 88 |
# File 'lib/mustermann/router.rb', line 84 def route(verb, pattern, target = nil, **, &block) raise ArgumentError, "need to provide target, :to or a block" unless target || block raise ArgumentError, "unknown verb: #{verb}" unless VERBS.include?(verb) @sets[verb].add(pattern, target || block) end |