Class: Jetra::RackAdapter

Inherits:
Object
  • Object
show all
Includes:
Rack::Utils
Defined in:
lib/jetra/adapter/rack.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, &custom_block) ⇒ RackAdapter

Returns a new instance of RackAdapter.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/jetra/adapter/rack.rb', line 11

def initialize(app, &custom_block)
  @app = app

  @routes = Set.new
  @app.routes.each_key do |route|
    @routes << route
  end

  @custom_block = custom_block

end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/jetra/adapter/rack.rb', line 23

def call(env)

  request = Rack::Request.new(env)

  route = request.path_info
  route.chop! if (char=route[-1]) and char=='/' # ignore last '/' char
  route[0] = '' if route[0]=="/" #remove first '/' char

  sym_route = route.to_sym

  params = indifferent_params(request.params)

  if @custom_block
    @custom_block.call(request, params)
  end

  if @routes.include?(sym_route)
    res = @app.call(sym_route, params)
  else
    params[:route] = route
    res = @app.call(:not_found, params)
  end

  result = {}
  result[:status] = res.status
  result[:body] = res.body

  ['200', {'Content-Type' => 'application/json;charset=utf-8'}, [result.to_json]]
end

#indifferent_hashObject

Creates a Hash with indifferent access.



68
69
70
# File 'lib/jetra/adapter/rack.rb', line 68

def indifferent_hash
  Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
end

#indifferent_params(object) ⇒ Object

Enable string or symbol key access to the nested params hash.



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/jetra/adapter/rack.rb', line 54

def indifferent_params(object)
  case object
  when Hash
    new_hash = indifferent_hash
    object.each { |key, value| new_hash[key] = indifferent_params(value) }
    new_hash
  when Array
    object.map { |item| indifferent_params(item) }
  else
    object
  end
end