Class: Krack::Router
- Inherits:
-
Object
- Object
- Krack::Router
- Defined in:
- lib/krack/router.rb
Instance Attribute Summary collapse
-
#routes ⇒ Object
readonly
Returns the value of attribute routes.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(&block) ⇒ Router
constructor
A new instance of Router.
- #map(verb, route, to) ⇒ Object
- #not_found ⇒ Object
Constructor Details
#initialize(&block) ⇒ Router
Returns a new instance of Router.
5 6 7 8 |
# File 'lib/krack/router.rb', line 5 def initialize(&block) @routes = [] instance_eval(&block) if block end |
Instance Attribute Details
#routes ⇒ Object (readonly)
Returns the value of attribute routes.
3 4 5 |
# File 'lib/krack/router.rb', line 3 def routes @routes end |
Instance Method Details
#call(env) ⇒ Object
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/krack/router.rb', line 10 def call(env) @routes.each do |verb, route, app| next unless verb == env["REQUEST_METHOD"] next unless match = env["PATH_INFO"].match(route) env["krack.params"] = Hash[match.names.zip(match.captures)] return app.call(env) end not_found end |
#map(verb, route, to) ⇒ Object
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/krack/router.rb', line 31 def map(verb, route, to) # Converts route params to regex named groups, like so: # "/deals/:id" -> "/deals/(?<id>\w+)" route.gsub!(/:\w+/) { |param| "(?<#{param[1..-1]}>\\w+)" } # Allow optional trailing slash, add start/end tokens route = "\\A#{route}\\/?\\z" @routes << [verb, Regexp.new(route), to] end |
#not_found ⇒ Object
21 22 23 |
# File 'lib/krack/router.rb', line 21 def not_found [404, {"Content-Type" => "text/plain"}, ["Not found"]] end |