Class: Jimson::Router::Map

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(opts = {}) ⇒ Map

Returns a new instance of Map.



10
11
12
13
14
# File 'lib/jimson/router/map.rb', line 10

def initialize(opts = {})
  @routes = {}
  @opts = opts
  @ns_sep = opts[:ns_sep] || '.'
end

Instance Method Details

#handler_for_method(method) ⇒ Object

Return the handler for a (possibly namespaced) method name



42
43
44
45
46
47
48
49
50
# File 'lib/jimson/router/map.rb', line 42

def handler_for_method(method)
  parts = method.split(@ns_sep)
  ns = (method.index(@ns_sep) == nil ? '' : parts.first)
  handler = @routes[ns]
  if handler.is_a?(Jimson::Router::Map)
    return handler.handler_for_method(parts[1..-1].join(@ns_sep))
  end
  handler
end

#jimson_methodsObject

Return an array of all methods on handlers in the map, fully namespaced



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/jimson/router/map.rb', line 62

def jimson_methods
  arr = @routes.keys.map do |ns|
    prefix = (ns == '' ? '' : "#{ns}#{@ns_sep}")
    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



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jimson/router/map.rb', line 27

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(@opts)
    @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’



19
20
21
22
# File 'lib/jimson/router/map.rb', line 19

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



55
56
57
# File 'lib/jimson/router/map.rb', line 55

def strip_method_namespace(method)
  method.split(@ns_sep).last
end