Class: Crystal::NamedRouter

Inherits:
Object show all
Defined in:
lib/crystal/router/named_router.rb

Defined Under Namespace

Modules: Helper

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNamedRouter

Returns a new instance of NamedRouter.



5
6
7
# File 'lib/crystal/router/named_router.rb', line 5

def initialize
  @names, @classes = {}, {}
end

Instance Attribute Details

#classesObject

Returns the value of attribute classes.



3
4
5
# File 'lib/crystal/router/named_router.rb', line 3

def classes
  @classes
end

#namesObject

Returns the value of attribute names.



3
4
5
# File 'lib/crystal/router/named_router.rb', line 3

def names
  @names
end

Instance Method Details

#add(name, klass) ⇒ Object



9
10
11
12
13
# File 'lib/crystal/router/named_router.rb', line 9

def add name, klass
  name = name.to_s
  names[name] = klass
  classes[klass] = name
end

#decode(path, params) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/crystal/router/named_router.rb', line 24

def decode path, params
  parts = path[1..-1].split '/'
  if parts.size >= 2
    method = parts.pop                
    name = parts.join('/')
                    
    if klass = names[name]
      return klass, method, params
    else
      nil
    end
  end
end

#encode(klass, method, params) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/crystal/router/named_router.rb', line 15

def encode klass, method, params
  if name = classes[klass]
    path = "/#{name}/#{method}"      
    return path, params
  else
    nil
  end
end

#encode_route_method(method, params = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/crystal/router/named_router.rb', line 38

def encode_route_method method, params = {}
  method = method.sub(/_path$/, '')
  names.each do |name, klass|
    if i = method.rindex(name)
      if method.size == i + name.size and method[(i-1)..(i-1)] == '_'
        return encode(klass, method[0..(i-2)], params)
      end
    end
  end
  raise "Unknown route #{method}!"
end