Class: FakePin::Rack

Inherits:
Object
  • Object
show all
Defined in:
lib/fake_pin/rack.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



6
7
8
9
10
11
12
13
14
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
# File 'lib/fake_pin/rack.rb', line 6

def call(env)
  request = ::Rack::Request.new(env)
  method  = env['REQUEST_METHOD']
  path    = env['PATH_INFO']

  # Strip the first slash if there is one. When mounted in Rails, there is no slash.
  # When running as a standlone rack app, there is one.
  path = path.gsub(/\A\//, '')

  params  = if env['CONTENT_TYPE'] == "application/json"
              Params.new(JSON.parse(request.body.read))
            else
              Params.new(request.params)
            end

  if path == "1/customers"
    if method == "POST"
      return render_response(201, Customer.create(params))
    end
  elsif path == "1/charges"
    if method == "POST"
      return render_response(201, Charge.create(params))
    end
  elsif path =~ /1\/cards(\.json)?/
    is_jsonp = (method == "GET" && params['_method'] == "POST")

    if method == "POST" || is_jsonp
      return render_response(201, Card.create(params), :callback => is_jsonp ? params['callback'] : nil)
    end
  end

  render_404
rescue Params::MissingParametersError => e
  messages = e.parameters.map do |param|
    { :code => "#{param}_invalid", :message => "#{param} is required", :param => param }
  end

  render_error 422, 'invalid_resource', 'One or more parameters were missing or invalid.', messages
rescue => e
  render_error 500, 'fake_pin_exception', "FakePin broke with: #{e.class.name}:#{e.message}"
end