Class: LocaSMS::RestClient
- Inherits:
-
Object
- Object
- LocaSMS::RestClient
- Defined in:
- lib/locasms/rest_client.rb
Overview
Class that handle http calls to LocaSMS api
Instance Attribute Summary collapse
-
#base_params ⇒ Object
Returns the value of attribute base_params.
-
#base_url ⇒ Object
Returns the value of attribute base_url.
Instance Method Summary collapse
-
#get(action, params = {}) ⇒ Hash
Performs a GET call for an action.
-
#initialize(base_url, base_params = {}) ⇒ RestClient
constructor
Creates a new instance of the RestClient class.
-
#params_for(action, params = {}) ⇒ Hash
Composes the parameters hash.
-
#parse_response(action, response) ⇒ Hash
Parses a result trying to get it in json.
Constructor Details
#initialize(base_url, base_params = {}) ⇒ RestClient
Creates a new instance of the RestClient class
16 17 18 19 |
# File 'lib/locasms/rest_client.rb', line 16 def initialize(base_url, base_params = {}) @base_url = base_url @base_params = base_params end |
Instance Attribute Details
#base_params ⇒ Object
Returns the value of attribute base_params.
11 12 13 |
# File 'lib/locasms/rest_client.rb', line 11 def base_params @base_params end |
#base_url ⇒ Object
Returns the value of attribute base_url.
11 12 13 |
# File 'lib/locasms/rest_client.rb', line 11 def base_url @base_url end |
Instance Method Details
#get(action, params = {}) ⇒ Hash
Performs a GET call for an action
44 45 46 47 48 49 50 51 52 |
# File 'lib/locasms/rest_client.rb', line 44 def get(action, params = {}) params = params_for action, params uri = URI.parse(base_url) uri.query = URI.encode_www_form(params) response = Net::HTTP.get_response(uri).body parse_response(action, response) end |
#params_for(action, params = {}) ⇒ Hash
Composes the parameters hash
67 68 69 |
# File 'lib/locasms/rest_client.rb', line 67 def params_for(action, params = {}) { action: action }.merge(base_params).merge(params).select { |_k, v| v } end |
#parse_response(action, response) ⇒ Hash
Parses a result trying to get it in json
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/locasms/rest_client.rb', line 77 def parse_response(action, response) raise InvalidOperation.new(action: action) if response.match?(/^0:OPERACAO INVALIDA$/i) j = begin MultiJson.load(response) rescue StandardError { 'status' => 1, 'data' => response, 'msg' => nil } end return j if (j['status'] == 1) || (action == :getstatus) raise InvalidLogin.new(action: action) if j['msg'].match?(/^falha ao realizar login$/i) raise LocaSMS::Exception.new(message: j['msg'], raw: response, action: action) end |