Class: BusinessCentral::Response::ResponseHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/business_central/response/response_handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dataset) ⇒ ResponseHandler

Constructor

Parameters:

  • dataset (Hash | Array)

    the result from the API operation



14
15
16
17
18
# File 'lib/business_central/response/response_handler.rb', line 14

def initialize(dataset)
  @compiled_data = []
  @dataset = dataset
  process
end

Instance Attribute Details

#compiled_dataObject

Returns the value of attribute compiled_data.



8
9
10
# File 'lib/business_central/response/response_handler.rb', line 8

def compiled_data
  @compiled_data
end

#datasetObject

Returns the value of attribute dataset.



7
8
9
# File 'lib/business_central/response/response_handler.rb', line 7

def dataset
  @dataset
end

Instance Method Details

#processObject

Compiles the data in the @dataset to the supplied class



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

def process
  @dataset.is_a?(Array) ? process_array : process_data(@dataset)
end

#process_arrayObject

If the supplied result from the API operation is an array, iterate over it and process each result into @compiled_data



29
30
31
# File 'lib/business_central/response/response_handler.rb', line 29

def process_array
  @dataset.each { |data| process_data(data) }
end

#process_data(data) ⇒ Object

Parse the JSON response from the API into an OpenStruct object. This will also parse any child objects, which allows the data to be accessed via regular chaining

eg

company.address.state

Parameters:

  • data (JSON)


42
43
44
45
46
47
48
49
# File 'lib/business_central/response/response_handler.rb', line 42

def process_data(data)
  new_record = JSON.parse(sanitize(data), object_class: OpenStruct)

  unless data["@odata.etag"].nil?
    new_record.etag = data["@odata.etag"]
  end
  @compiled_data << new_record
end

#sanitize(data) ⇒ Object

Ensures the data is in JSON format



53
54
55
# File 'lib/business_central/response/response_handler.rb', line 53

def sanitize(data)
  data.is_a?(Hash) ? data.to_json : data
end