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.
48 49 50 51 52 53 54 |
# File 'lib/mustermann/router.rb', line 48 def initialize(fallback = nil, key: "mustermann.match", **, &block) @key = key @sets = VERBS.to_h { |verb| [verb, Set.new] } @options = @fallback = fallback || ->(env) { NOT_FOUND.dup } instance_exec(&block) if block_given? end |
Instance Method Details
#call(env) ⇒ Array
Returns The Rack response array (status, headers, body).
58 59 60 61 62 63 64 |
# File 'lib/mustermann/router.rb', line 58 def call(env) if routes = @sets[env["REQUEST_METHOD"]] and match = routes.match(env["PATH_INFO"] || "/") env = env.merge(@key => match) return match.value.call(env) end @fallback.call(env) end |
#fallback(fallback = nil, &block) ⇒ Object
66 |
# File 'lib/mustermann/router.rb', line 66 def fallback(fallback = nil, &block) = @fallback = fallback || block || @fallback |
#path_for(app, behavior = nil, params = {}) ⇒ String
Helps generate links
90 91 92 93 |
# File 'lib/mustermann/router.rb', line 90 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.
78 79 80 81 82 83 |
# File 'lib/mustermann/router.rb', line 78 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) pattern = Mustermann.new(pattern, **@options, **) @sets[verb].add(pattern, target || block) end |