Class: Dialers::Transformable

Inherits:
Object
  • Object
show all
Defined in:
lib/dialers/transformable.rb

Overview

This class provide some ways to transform a reponse into an object or a set of objects based on what objects the user of this class wants to provide.

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Transformable


5
6
7
8
# File 'lib/dialers/transformable.rb', line 5

def initialize(response)
  self.response = response
  self.raw_data = response.body
end

Instance Method Details

#as_receivedHash, Array

Returns the raw body of the request.


48
49
50
# File 'lib/dialers/transformable.rb', line 48

def as_received
  raw_data
end

#transform_to_many(entity_class_or_decider, root: nil) ⇒ Array<Object>

Transforms a response into many objects based on the response's body.


38
39
40
41
42
43
44
# File 'lib/dialers/transformable.rb', line 38

def transform_to_many(entity_class_or_decider, root: nil)
  items = get_rooted_items(root)
  unless items.is_a?(Array)
    fail Dialers::ImpossibleTranformationError.new(response)
  end
  items.map { |item| transform_attributes_to_object(entity_class_or_decider, item) }
end

#transform_to_one(entity_class_or_decider, root: nil) ⇒ Object

Transforms a response into one object based on the response's body.

If you pass a hash like this:

{ 200 => ProductCreated, 202 => ProductAccepted }

the transformation will decide which object to create based on the status.

It's important to note that the class must provide attribute writers for this method to be able to fill an object with the responses's body data.


26
27
28
29
# File 'lib/dialers/transformable.rb', line 26

def transform_to_one(entity_class_or_decider, root: nil)
  object = root ? raw_data[root] : raw_data
  transform_attributes_to_object(entity_class_or_decider, object)
end