Class: Mustermann::Router::Simple
- Inherits:
-
Object
- Object
- Mustermann::Router::Simple
- Defined in:
- lib/mustermann/router/simple.rb
Overview
Simple pattern based router that allows matching a string to a given callback.
Instance Attribute Summary collapse
-
#default ⇒ Object
Default value for when no pattern matches.
Instance Method Summary collapse
-
#[](string) ⇒ #call?
Callback for given string, if a pattern matches.
- #[]=(pattern, callback) ⇒ Object
-
#call(input, &fallback) ⇒ Object
Finds the matching callback and calls ‘call` on it with the given input and the params.
-
#initialize(default: nil, **options, &block) ⇒ Mustermann::Router::Simple
constructor
New router instance.
- #on(*patterns, call: Proc.new, **options) ⇒ Object
Constructor Details
#initialize(default: nil, **options, &block) ⇒ Mustermann::Router::Simple
Returns new router instance.
54 55 56 57 58 59 60 |
# File 'lib/mustermann/router/simple.rb', line 54 def initialize(default: nil, **, &block) @options = @map = [] @default = default block.arity == 0 ? instance_eval(&block) : yield(self) if block end |
Instance Attribute Details
#default ⇒ Object
Default value for when no pattern matches
25 26 27 |
# File 'lib/mustermann/router/simple.rb', line 25 def default @default end |
Instance Method Details
#[](string) ⇒ #call?
Returns callback for given string, if a pattern matches.
71 72 73 74 |
# File 'lib/mustermann/router/simple.rb', line 71 def [](string) string = string_for(string) unless string.is_a? String @map.detect { |p,v| p === string }[1] end |
#[]=(pattern, callback) ⇒ Object
86 87 88 |
# File 'lib/mustermann/router/simple.rb', line 86 def []=(pattern, callback) on(pattern, call: callback) end |
#call(input, &fallback) ⇒ Object
Finds the matching callback and calls ‘call` on it with the given input and the params.
121 122 123 124 125 126 127 128 129 |
# File 'lib/mustermann/router/simple.rb', line 121 def call(input, &fallback) @map.each do |pattern, callback| catch(:pass) do next unless params = pattern.params(string_for(input)) return invoke(callback, input, params, pattern) end end @default end |
#on(*patterns, call: Proc.new, **options) ⇒ Object
112 113 114 115 116 117 |
# File 'lib/mustermann/router/simple.rb', line 112 def on(*patterns, call: Proc.new, **) patterns.each do |pattern| pattern = Mustermann.new(pattern.to_str, **, **@options) if pattern.respond_to? :to_str @map << [pattern, call] end end |