Class: NYNY::Router
- Inherits:
-
Object
- Object
- NYNY::Router
- Defined in:
- lib/nyny/router.rb
Constant Summary collapse
- NullHandler =
Class.new
Instance Attribute Summary collapse
-
#after_hooks ⇒ Object
readonly
Returns the value of attribute after_hooks.
-
#before_hooks ⇒ Object
readonly
Returns the value of attribute before_hooks.
-
#fallback ⇒ Object
readonly
Returns the value of attribute fallback.
-
#routes ⇒ Object
readonly
Returns the value of attribute routes.
Instance Method Summary collapse
- #call(env) ⇒ Object
- #find_handler(request) ⇒ Object
-
#initialize(options) ⇒ Router
constructor
A new instance of Router.
- #prepare_params(request, url_params) ⇒ Object
- #process(request, handler) ⇒ Object
Constructor Details
#initialize(options) ⇒ Router
Returns a new instance of Router.
6 7 8 9 10 11 |
# File 'lib/nyny/router.rb', line 6 def initialize @fallback = [:fallback] @routes = [:routes] @before_hooks = [:before_hooks] @after_hooks = [:after_hooks] end |
Instance Attribute Details
#after_hooks ⇒ Object (readonly)
Returns the value of attribute after_hooks.
5 6 7 |
# File 'lib/nyny/router.rb', line 5 def after_hooks @after_hooks end |
#before_hooks ⇒ Object (readonly)
Returns the value of attribute before_hooks.
5 6 7 |
# File 'lib/nyny/router.rb', line 5 def before_hooks @before_hooks end |
#fallback ⇒ Object (readonly)
Returns the value of attribute fallback.
5 6 7 |
# File 'lib/nyny/router.rb', line 5 def fallback @fallback end |
#routes ⇒ Object (readonly)
Returns the value of attribute routes.
5 6 7 |
# File 'lib/nyny/router.rb', line 5 def routes @routes end |
Instance Method Details
#call(env) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/nyny/router.rb', line 22 def call env req = Request.new(env) handler, params = find_handler req if handler != NullHandler prepare_params req, params process req, handler else fallback.call env end end |
#find_handler(request) ⇒ Object
13 14 15 16 17 18 19 20 |
# File 'lib/nyny/router.rb', line 13 def find_handler request routes.fetch(request.request_method.downcase.to_sym, []).each do |sig, h| params = sig.match request.path return [h, params] if params end [NullHandler, {}] end |
#prepare_params(request, url_params) ⇒ Object
34 35 36 37 |
# File 'lib/nyny/router.rb', line 34 def prepare_params request, url_params request.params.merge! url_params request.params.default_proc = proc {|h,k| h[k.to_s] || h[k.to_sym]} end |
#process(request, handler) ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/nyny/router.rb', line 39 def process request, handler scope = RequestScope.new(request) catch (:halt) do before_hooks.each {|h| scope.instance_eval &h } response = scope.apply_to &handler after_hooks.each {|h| scope.instance_eval &h } response end end |