Class: Jimson::Router::Map
- Inherits:
-
Object
- Object
- Jimson::Router::Map
- Defined in:
- lib/jimson/router/map.rb
Overview
Provides a DSL for routing method namespaces to handlers. Only handles root-level and non-nested namespaces, e.g. ‘foo.bar’ or ‘foo’.
Instance Method Summary collapse
-
#handler_for_method(method) ⇒ Object
Return the handler for a (possibly namespaced) method name.
-
#initialize ⇒ Map
constructor
A new instance of Map.
-
#jimson_methods ⇒ Object
Return an array of all methods on handlers in the map, fully namespaced.
-
#namespace(ns, handler = nil, &block) ⇒ Object
Define the handler for a namespace.
-
#root(handler) ⇒ Object
Set the root handler, i.e.
-
#strip_method_namespace(method) ⇒ Object
Strip off the namespace part of a method and return the bare method name.
Constructor Details
#initialize ⇒ Map
Returns a new instance of Map.
10 11 12 |
# File 'lib/jimson/router/map.rb', line 10 def initialize @routes = {} end |
Instance Method Details
#handler_for_method(method) ⇒ Object
Return the handler for a (possibly namespaced) method name
40 41 42 43 44 45 46 47 48 |
# File 'lib/jimson/router/map.rb', line 40 def handler_for_method(method) parts = method.split('.') ns = (method.index('.') == nil ? '' : parts.first) handler = @routes[ns] if handler.is_a?(Jimson::Router::Map) return handler.handler_for_method(parts[1..-1].join('.')) end handler end |
#jimson_methods ⇒ Object
Return an array of all methods on handlers in the map, fully namespaced
60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/jimson/router/map.rb', line 60 def jimson_methods arr = @routes.keys.map do |ns| prefix = (ns == '' ? '' : "#{ns}.") handler = @routes[ns] if handler.is_a?(Jimson::Router::Map) handler.jimson_methods else handler.class.jimson_exposed_methods.map { |method| prefix + method } end end arr.flatten end |
#namespace(ns, handler = nil, &block) ⇒ Object
Define the handler for a namespace
25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/jimson/router/map.rb', line 25 def namespace(ns, handler = nil, &block) if !!handler handler = handler.new if handler.is_a?(Class) @routes[ns.to_s] = handler else # passed a block for nested namespacing map = Jimson::Router::Map.new @routes[ns.to_s] = map map.instance_eval &block end end |
#root(handler) ⇒ Object
Set the root handler, i.e. the handler used for a bare method like ‘foo’
17 18 19 20 |
# File 'lib/jimson/router/map.rb', line 17 def root(handler) handler = handler.new if handler.is_a?(Class) @routes[''] = handler end |
#strip_method_namespace(method) ⇒ Object
Strip off the namespace part of a method and return the bare method name
53 54 55 |
# File 'lib/jimson/router/map.rb', line 53 def strip_method_namespace(method) method.split('.').last end |