Class: InfomemeClient::Response

Inherits:
EntityHash show all
Defined in:
lib/infomeme_client/response.rb

Constant Summary collapse

STATUS_FAILED =
-1
STATUS_OK =
0
STATUS_ERROR =
1
ERRORS =
{
  "request_failed" => InfomemeClient::Error::RequestFailed,
  "error" => InfomemeClient::Error,
  "internal_error" => InfomemeClient::Error::InternalError,
  "no_access" => InfomemeClient::Error::NoAccess,
  "not_found" => InfomemeClient::Error::NotFound,
}.freeze

Instance Method Summary collapse

Methods inherited from EntityHash

#freeze, #id, #method_missing, #respond_to?, #to_hash

Constructor Details

#initialize(response) ⇒ Response

Returns a new instance of Response.



14
15
16
17
18
19
20
# File 'lib/infomeme_client/response.rb', line 14

def initialize(response)
  super(response.is_a?(Exception) ? {:status => STATUS_FAILED, :message => "Request failed.", :error_code => "request_failed", :errors => {:base => {response.class.name.to_sym => response.message}}} : response, true)
  ERRORS.each do |key, val|
    instance_eval "def #{val.name.split('::').last.sub(/\b\w/) { $&.downcase }}Error?; error_code == #{key}; end"
  end
  freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class InfomemeClient::EntityHash

Instance Method Details

#error?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/infomeme_client/response.rb', line 26

def error?
  status != STATUS_OK
end

#extract(key, *extra_args) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/infomeme_client/response.rb', line 38

def extract(key, *extra_args)
  return nil unless @hsh.key?(key)
  klass = case key
  when :comments then InfomemeClient::EntityHash::Comment
  when :meme, :memes then InfomemeClient::EntityHash::Meme
  when :meme_types then InfomemeClient::EntityHash::MemeType
  when :user then InfomemeClient::EntityHash::User
  when :transactions then InfomemeClient::EntityHash::Transaction
  when :invoice, :invoices then InfomemeClient::EntityHash::Invoice
  else InfomemeClient::EntityHash
  end
  stored = to_hash[key]
  stored.is_a?(Array) ? stored.collect {|val| klass.new *[val, extra_args]} : klass.new(*[stored, extra_args])
end

#failed?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/infomeme_client/response.rb', line 22

def failed?
  status == STATUS_FAILED
end

#raise_error(options = {}) ⇒ Object

Raises:

  • (err)


30
31
32
33
34
35
36
# File 'lib/infomeme_client/response.rb', line 30

def raise_error(options = {})
  return false unless error?
  return false if options.key?(:only) && ! options[:only].include?(error_code)
  return false if options.key?(:except) && options[:except].include?(error_code)
  err = ERRORS.key?(error_code) ? ERRORS[error_code] : InfomemeClient::Error
  raise err, [(respond_to?(:errors) ? errors.to_hash : nil), message]
end