Module: SmswayApi::API

Defined in:
lib/smsway_api/api.rb

Constant Summary collapse

URL_PREFIX =
'http://my.smsway.ru/'
DEFAULT_HEADERS =
{"Content-Type" => "text/xml; charset=utf-8"}

Class Method Summary collapse

Class Method Details

.call(method, options = {}) ⇒ Object



7
8
9
10
# File 'lib/smsway_api/api.rb', line 7

def call(method, options = {})
  xml = build(method, options)
  request({url: URL, headers: HEADERS, request: xml})
end

.method_missing(name, *args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/smsway_api/api.rb', line 32

def method_missing name, *args
  api_method = "SmswayApi::Method::#{name.to_s.camelize}".constantize.new(*args)
  api_method.build_xml
  response = request({
    path: api_method.uri,
    request: api_method.build_xml
  })
  api_method.parse(response)
rescue NameError
  super
end

.request(options) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/smsway_api/api.rb', line 12

def request options
  headers = options.delete(:headers) || {}

  uri = URI.parse(URL_PREFIX+options.delete(:path))
  http = Net::HTTP.new(uri.host, uri.port)

  req = Net::HTTP::Post.new(uri.path, DEFAULT_HEADERS.merge(headers))
  req.body = options.delete(:request)
  response = http.request(req).body
  if SmswayApi.log_requests
    SmswayApi.logger.debug("[smswayapi] request \n #{req.body}")
  end
  if SmswayApi.log_responses
    # hint to prevent "log writing failed. "\xD0" from ASCII-8BIT to UTF-8" error
    debug_response = response.encode('utf-8', :invalid => :replace, :undef => :replace, :replace => '_')
    SmswayApi.logger.debug("[smswayapi] response \n #{debug_response}")
  end
  response
end