Module: AppRoutes

Defined in:
lib/app-routes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#get_routesObject

Returns the value of attribute get_routes


8
9
10
# File 'lib/app-routes.rb', line 8

def get_routes
  @get_routes
end

#post_routesObject

Returns the value of attribute post_routes


8
9
10
# File 'lib/app-routes.rb', line 8

def post_routes
  @post_routes
end

Instance Method Details

#add_route(arg, request_method = 'GET') ⇒ Object


66
67
68
69
# File 'lib/app-routes.rb', line 66

def add_route(arg, request_method='GET')
  name = request_method == 'GET' ? :get : :post
  method(name).call(arg) {yield(@params)}
end

#get(arg, &block) ⇒ Object


56
57
58
59
# File 'lib/app-routes.rb', line 56

def get(arg,&block)
  methodx = {String: :string_get, Regexp: :regex_get}
  send (methodx[arg.class.to_s.to_sym]), arg, &block 
end

#initialize(logfile = '/tmp/app-routes.log') ⇒ Object


10
11
12
13
# File 'lib/app-routes.rb', line 10

def initialize(logfile='/tmp/app-routes.log')
  @get_routes, @post_routes = {}, {}
  @params = {}
end

#post(arg, &block) ⇒ Object


61
62
63
64
# File 'lib/app-routes.rb', line 61

def post(arg,&block)
  methodx = {String: :string_post, Regexp: :regex_post}
  send (methodx[arg.class.to_s.to_sym]), arg, &block 
end

#run_route(request, request_method = 'GET') ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/app-routes.rb', line 15

def run_route(request, request_method='GET')

  result = nil

  return unless @get_routes or @post_routes

  route, routes = case request_method
    when 'GET'
      [@get_routes.detect {|key, block|  request.match(key) }, @get_routes]
    when 'POST'
      [@post_routes.detect {|key, block|  request.match(key) }, @post_routes]
  end
  
  if route then
    key, block = route      
    match = request.match(key)

    args = match.captures
    @params[:captures] = *args

    if routes[key][:s] then
      raw_params = routes[key][:s].gsub(':','').match(key).captures

      splat, raw_params2 = raw_params.each_with_index.partition {|x,i| x == '/*'}
      @params[:splat] = splat.map {|x,i| v = args[i]; args.delete_at(i); v}

      @params.merge!(Hash[raw_params2.map{|x,i| x.to_sym}.zip(args)])
    end 

    begin
      result = routes[key][:block].call *args
    rescue Exception => e  

      err_label = e.message + " :: \n" + e.backtrace.join("\n")      
      raise 'app-routes: ' + request.inspect + ' ' + err_label
    end      
    
  end
  result
end