Module: Kazoo::Router::Common

Included in:
App
Defined in:
lib/kazoo/router/common.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



5
6
7
# File 'lib/kazoo/router/common.rb', line 5

def self.included(klass)
  klass.send(:extend, ClassMethods)
end

Instance Method Details

#add_route(route, name = nil) ⇒ Object



44
45
46
47
# File 'lib/kazoo/router/common.rb', line 44

def add_route(route, name=nil)
  routes << route
  named_routes[name.to_sym] = route if name
end

#call(env) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/kazoo/router/common.rb', line 61

def call(env)
  @env = env
  kenv['params'] ||= {}
  
  #TODO: This hack is causing problems. Figure out regexp to match paths better. 
  env['PATH_INFO'] = "#{env["PATH_INFO"]}/" unless %r'/$'.match(env['PATH_INFO'])
  
  @routes.each do |route|
    
    params = route.extract_params(env['PATH_INFO'])
    
    if params && route.app
      kenv['params'].merge!(params)
      
      match = route.to_regexp.match(env['PATH_INFO'])[0]
      kenv['path_prefix'] = kenv['path_prefix'] ? File.join(kenv['path_prefix'], match) : match
      
      env['PATH_INFO'] = env['PATH_INFO'].sub(match, '')
      env['PATH_INFO'] = "/#{env['PATH_INFO']}" unless env['PATH_INFO'].match(%r'^/')
      
      response = route.app.call(env)
      
      if response[1]['X-Cascade'] == 'pass'
        next 
      elsif @error_handler && response[0] > 399
        return @error_handler.call(env, *response)
      else
        return response
      end
      
    elsif get(:mode) == :app && params
      return params
    end
    
  end
  
  # If no routes found
  default_response = [404, {'Content-Type' => 'text/plain', "X-Cascade" => "pass"}, 'The requested URI is not found']
  @error_handler ?  @error_handler.call(env, *default_response) :  default_response
end

#get(var) ⇒ Object



32
33
34
35
# File 'lib/kazoo/router/common.rb', line 32

def get(var)
  @_settings ||= {}
  @_settings[var.to_sym] || self.class.get(var)
end

#kenvObject



57
58
59
# File 'lib/kazoo/router/common.rb', line 57

def kenv
  @env['kazoo'] ||= {}
end

#map(opts = {}, &blk) ⇒ Object



37
38
39
40
41
42
# File 'lib/kazoo/router/common.rb', line 37

def map(opts = {}, &blk)
  opts = self.class.context_options.merge(opts) if self.class.context_options
  @context ||= Context.new(self, opts)
  @context.instance_eval(&blk)
  self
end

#named_routesObject



53
54
55
# File 'lib/kazoo/router/common.rb', line 53

def named_routes
  @named_routes ||= {}
end

#routesObject



49
50
51
# File 'lib/kazoo/router/common.rb', line 49

def routes
  @routes ||= []
end

#set(var, val) ⇒ Object

ClassMethods



27
28
29
30
# File 'lib/kazoo/router/common.rb', line 27

def set(var,val)
  @_settings ||= {}
  @_settings[var.to_sym] = val
end