Class: Mustermann::Router::Simple
- Inherits:
-
Object
- Object
- Mustermann::Router::Simple
- Defined in:
- lib/praxis/router/simple.rb
Overview
Simple pattern based router that allows matching a string to a given callback.
Direct Known Subclasses
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) ⇒ 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.
58 59 60 61 62 63 64 |
# File 'lib/praxis/router/simple.rb', line 58 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
29 30 31 |
# File 'lib/praxis/router/simple.rb', line 29 def default @default end |
Instance Method Details
#[](string) ⇒ #call?
Returns callback for given string, if a pattern matches.
75 76 77 78 |
# File 'lib/praxis/router/simple.rb', line 75 def [](string) string = string_for(string) unless string.is_a? String @map.detect { |p,v| p === string }[1] end |
#[]=(pattern, callback) ⇒ Object
90 91 92 |
# File 'lib/praxis/router/simple.rb', line 90 def []=(pattern, callback) on(pattern, call: callback) end |
#call(input) ⇒ Object
Finds the matching callback and calls ‘call` on it with the given input and the params.
125 126 127 128 129 130 131 132 133 |
# File 'lib/praxis/router/simple.rb', line 125 def call(input) @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
116 117 118 119 120 121 |
# File 'lib/praxis/router/simple.rb', line 116 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 |