class Naver::Searchad::Api::Core::ApiCommand

Constants

ERROR_CODE_MAPPING

More error codes can be found at the below url github.com/naver/searchad-apidoc/blob/master/NaverSA_API_Error_Code_MAP.md

JSON_CONTENT_TYPE

Attributes

decode_snake_case[RW]
request_object[RW]

Public Class Methods

new(method, url, body: nil, decode_snake_case: true) click to toggle source
Calls superclass method
# File lib/naver/searchad/api/core/api_command.rb, line 23
def initialize(method, url, body: nil, decode_snake_case: true)
  super(method, url, body: body)

  @decode_snake_case = decode_snake_case
end

Public Instance Methods

check_status(status, header = nil, body = nil, message = nil) click to toggle source
Calls superclass method
# File lib/naver/searchad/api/core/api_command.rb, line 50
def check_status(status, header = nil, body = nil, message = nil)
  case status
  when 400, 402..500
    code, message = parse_error(body)
    raise ERROR_CODE_MAPPING[code].new(
      message,
      status_code: status,
      header: header,
      body: body
    ) if ERROR_CODE_MAPPING.key?(code)
  end

  super(status, header, body, message)
end
decode_response_body(content_type, body) click to toggle source
Calls superclass method
# File lib/naver/searchad/api/core/api_command.rb, line 37
def decode_response_body(content_type, body)
  return super unless content_type
  return nil unless content_type.start_with?(JSON_CONTENT_TYPE)

  decoded_response = JSON.parse(body)
  deep_snake_case_params!(decoded_response) if @decode_snake_case
  if decoded_response.kind_of?(Hash)
    OpenStruct.new(decoded_response)
  elsif decoded_response.kind_of?(Array)
    decoded_response.map { |h| OpenStruct.new(h) }
  end
end
prepare!() click to toggle source
Calls superclass method
# File lib/naver/searchad/api/core/api_command.rb, line 29
def prepare!
  if request_object
    self.header['Content-Type'] ||= JSON_CONTENT_TYPE
    self.body = request_object.to_json
  end
  super
end

Private Instance Methods

deep_snake_case_params!(val) click to toggle source
# File lib/naver/searchad/api/core/api_command.rb, line 67
def deep_snake_case_params!(val)
  case val
  when Array
    val.map {|v| deep_snake_case_params! v }
  when Hash
    val.keys.each do |k, v = val[k]|
      val.delete k
      val[to_snake_case(k)] = deep_snake_case_params!(v)
    end
    val
  else
    val
  end
end
parse_error(body) click to toggle source
# File lib/naver/searchad/api/core/api_command.rb, line 90
def parse_error(body)
  obj = JSON.parse(body)
  message = obj['title']
  message << ", #{obj['detail']}" if obj['detail']

  [obj['code'].to_s, message]
rescue
  [nil, nil]
end
to_snake_case(str) click to toggle source
# File lib/naver/searchad/api/core/api_command.rb, line 82
def to_snake_case(str)
  str.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
      gsub(/([a-z\d])([A-Z])/,'\1_\2').
        tr("-", "_").
          downcase
end