Module: Transbank::Onepay::Utils::NetHelper

Included in:
Refund, Transaction
Defined in:
lib/transbank/sdk/onepay/utils/net_helper.rb

Instance Method Summary collapse

Instance Method Details

#http_post(uri_string, body) ⇒ Hash

POST a request to Transbank’s servers, and return the parsed response

Parameters:

  • uri_string (String)

    an URI to post to

  • body (Hash)

    the body of your POST request

Returns:

  • (Hash)

    the JSON.parse’d response body



9
10
11
12
13
14
15
16
17
18
# File 'lib/transbank/sdk/onepay/utils/net_helper.rb', line 9

def http_post(uri_string, body)
  uri = URI.parse(uri_string)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  request = Net::HTTP::Post.new(uri.path, 'Content-Type'=> 'application/json')
  camel_cased_body = keys_to_camel_case(body)
  request.body = JSON.generate(camel_cased_body)
  result = http.request(request)
  JSON.parse(result.body)
end

#keys_to_camel_case(hash) ⇒ Object

Required for sending data to Transbank.



21
22
23
24
25
26
27
28
29
30
# File 'lib/transbank/sdk/onepay/utils/net_helper.rb', line 21

def keys_to_camel_case(hash)
  hash.reduce({}) do |new_hash, (key, val)|
    if val.is_a? Array
      val = val.map {|value| value.is_a?(Hash) ? keys_to_camel_case(value) : value }
    end
    new_key = snake_to_camel_case(key.to_s)
    new_hash[new_key] = val
    new_hash
  end
end

#snake_to_camel_case(str) ⇒ Object



32
33
34
# File 'lib/transbank/sdk/onepay/utils/net_helper.rb', line 32

def snake_to_camel_case(str)
  str.split('_').reduce { |string, current_word| string + current_word.capitalize }
end