Class: CampingRouting

Inherits:
Object
  • Object
show all
Extended by:
StringUtils
Defined in:
lib/routing/camping.rb

Overview

A web server with Camping-style routing

class CampingExample < CampingRouting

class Index
  def get
    ...
  end
end

class X
  def get
    ...
  end
end

end

Class Method Summary collapse

Instance Method Summary collapse

Methods included from StringUtils

snake_of_pascal

Class Method Details

.const_added(const_name) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/routing/camping.rb', line 29

def const_added(const_name)
  klass = const_get(const_name)
  instance = klass.new

  # TODO: Handle post/patch/delete/etc
  routes << { method: 'GET',
              pattern: regexp_of_name(const_name),
              instance: instance }
end

.regex_of_part(part) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/routing/camping.rb', line 39

def regex_of_part(part)
  case part
  when 'x'
    '(\w+)'
  when 'n'
    '(\d+)'
  else
    part
  end
end

.regexp_of_name(const_name) ⇒ Object

:HelloWorld => ^/hello/world$ :HelloXWorld => ^/hello/(\w+)/world$



53
54
55
56
57
58
59
60
61
# File 'lib/routing/camping.rb', line 53

def regexp_of_name(const_name)
  return %r{^/$} if const_name == :Index

  regexp_str = snake_of_pascal(const_name.to_s)
               .split('_')
               .map { |part| regex_of_part(part) }
               .join('/')
  Regexp.new("^/#{regexp_str}$")
end

.routesObject



25
26
27
# File 'lib/routing/camping.rb', line 25

def routes
  @routes ||= []
end

Instance Method Details

#call(env) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/routing/camping.rb', line 64

def call(env)
  route = self.class.routes.find do |route|
    route[:method] == env['REQUEST_METHOD'] and route[:pattern] =~ env['PATH_INFO']
  end

  if route
    result = route[:instance].send(:get, *Regexp.last_match.captures)
    [200, { 'content-type' => 'text/html' }, [result]]
  else
    [404, { 'content-type' => 'text/html' }, ['404 Not Found']]
  end
end