Class: RESTinPeace::ResponseConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/rest_in_peace/response_converter.rb

Defined Under Namespace

Classes: UnknownConvertStrategy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response, instance_or_class) ⇒ ResponseConverter

Returns a new instance of ResponseConverter.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rest_in_peace/response_converter.rb', line 11

def initialize(response, instance_or_class)
  self.body = response.body

  if instance_or_class.respond_to?(:new)
    self.klass = instance_or_class
    self.existing_instance = new_instance
  else
    self.klass = instance_or_class.class
    self.existing_instance = instance_or_class
  end
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



9
10
11
# File 'lib/rest_in_peace/response_converter.rb', line 9

def body
  @body
end

#existing_instanceObject

Returns the value of attribute existing_instance.



9
10
11
# File 'lib/rest_in_peace/response_converter.rb', line 9

def existing_instance
  @existing_instance
end

#klassObject

Returns the value of attribute klass.



9
10
11
# File 'lib/rest_in_peace/response_converter.rb', line 9

def klass
  @klass
end

Instance Method Details

#convert_from_arrayObject



38
39
40
41
42
# File 'lib/rest_in_peace/response_converter.rb', line 38

def convert_from_array
  body.map do |entity|
    convert_from_hash(entity, new_instance)
  end
end

#convert_from_hash(entity = body, instance = existing_instance) ⇒ Object



44
45
46
47
# File 'lib/rest_in_peace/response_converter.rb', line 44

def convert_from_hash(entity = body, instance = existing_instance)
  instance.force_attributes_from_hash entity
  instance
end

#new_instanceObject



49
50
51
# File 'lib/rest_in_peace/response_converter.rb', line 49

def new_instance
  klass.new
end

#resultObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rest_in_peace/response_converter.rb', line 23

def result
  case body.class.to_s
  when 'Array'
    convert_from_array
  when 'Hash'
    convert_from_hash
  when 'String'
    body
  when 'NilClass'
    nil
  else
    raise UnknownConvertStrategy, body.class
  end
end