Class: Easy::Api::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/easy/api/result.rb

Overview

Encapsulates the response data of an API call

Expected values to be added are: #status_code success error (see Easy::Api::Error#new)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeResult



15
16
17
# File 'lib/easy/api/result.rb', line 15

def initialize
  @native_attributes = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object



84
85
86
87
88
89
90
91
# File 'lib/easy/api/result.rb', line 84

def method_missing(symbol, *args)
  if symbol =~ /.+=/
    attr_name = symbol.to_s[0..-2]
    @native_attributes[attr_name] = args.first
  else
    super
  end
end

Instance Attribute Details

#errorEasy::Api::Error?

An instance of Easy::Api::Error or nil if there is no error



21
22
23
# File 'lib/easy/api/result.rb', line 21

def error
  @error
end

#status_codeInteger

The HTTP status code to respond with

Raises:

  • StandardError if status_code has not been set



34
35
36
# File 'lib/easy/api/result.rb', line 34

def status_code
  @status_code || raise("Easy::Api::Result needs a status_code!")
end

#successtrue, false

Represents whether the request succeeded or not



27
28
29
# File 'lib/easy/api/result.rb', line 27

def success
  @success || false
end

Instance Method Details

#rawObject



38
39
40
# File 'lib/easy/api/result.rb', line 38

def raw
  @raw ||= RawAttributesResult.new
end

#to_json(options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/easy/api/result.rb', line 42

def to_json(options={})
  json = non_raw_attributes.to_json

  if raw.attributes.any?
    json = json.chop # remove the closing '}'

    raw.attributes.each_with_index do |(attr_name, raw_value), index|
      json << ','

      json << '"' << attr_name << '":' << raw_value
    end

    json << '}'
  end

  json
end

#to_xml(options = {}) ⇒ Hash

Used by Rails to parse the result as xml

Will always contain ‘success’, the error if there is one, and any dynamic attributes.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/easy/api/result.rb', line 64

def to_xml(options={})
  options = options.dup
  options[:root]        ||= 'response'
  options[:skip_types]  ||= true

  xml = non_raw_attributes.to_xml(options)

  if raw.attributes.any?
    xml.gsub!(/<\/#{options[:root]}>[\s\n]*\z/, '') # remove the closing </response>

    raw.attributes.each_with_index do |(attr_name, raw_value), index|
      xml << '<' << attr_name << '>' << raw_value << '</' << attr_name << '>'
    end

    xml << "</#{options[:root]}>"
  end

  xml
end