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

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

  @custom_block = custom_block

end

Instance Method Details

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/jetra/adapter/rack.rb', line 18

def call(env)

  request = Rack::Request.new(env)

  params = indifferent_params(request.params)

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

  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

  res = @app.call(sym_route, params)

  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.



58
59
60
# File 'lib/jetra/adapter/rack.rb', line 58

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.



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jetra/adapter/rack.rb', line 44

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