Class: AMEE::Data::Item

Inherits:
Object show all
Defined in:
lib/amee/data_item.rb

Instance Attribute Summary collapse

Attributes inherited from Object

#path

Attributes inherited from Object

#connection, #created, #modified, #name, #path, #uid

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Object

#full_path

Methods included from ParseHelper

#xmlpathpreamble

Constructor Details

#initialize(data = {}) ⇒ Item

Returns a new instance of Item.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/amee/data_item.rb', line 7

def initialize(data = {})
  @values = data[:values]
  @choices = data[:choices]
  @label = data[:label]
  @item_definition_uid = data[:item_definition]
  @total_amount = data[:total_amount]
  @total_amount_unit = data[:total_amount_unit]
  @start_date = data[:start_date]
  @category_uid = data[:category_uid]
  super
end

Instance Attribute Details

#category_uidObject (readonly)

Returns the value of attribute category_uid.



25
26
27
# File 'lib/amee/data_item.rb', line 25

def category_uid
  @category_uid
end

#choicesObject (readonly)

Returns the value of attribute choices.



20
21
22
# File 'lib/amee/data_item.rb', line 20

def choices
  @choices
end

#item_definition_uidObject (readonly)

Returns the value of attribute item_definition_uid.



26
27
28
# File 'lib/amee/data_item.rb', line 26

def item_definition_uid
  @item_definition_uid
end

#labelObject (readonly)

Returns the value of attribute label.



21
22
23
# File 'lib/amee/data_item.rb', line 21

def label
  @label
end

#start_dateObject (readonly)

Returns the value of attribute start_date.



24
25
26
# File 'lib/amee/data_item.rb', line 24

def start_date
  @start_date
end

#total_amountObject (readonly)

Returns the value of attribute total_amount.



22
23
24
# File 'lib/amee/data_item.rb', line 22

def total_amount
  @total_amount
end

#total_amount_unitObject (readonly)

Returns the value of attribute total_amount_unit.



23
24
25
# File 'lib/amee/data_item.rb', line 23

def total_amount_unit
  @total_amount_unit
end

#valuesObject (readonly)

Returns the value of attribute values.



19
20
21
# File 'lib/amee/data_item.rb', line 19

def values
  @values
end

Class Method Details

.create(category, options = {}) ⇒ Object



166
167
168
# File 'lib/amee/data_item.rb', line 166

def self.create(category, options = {})
  create_without_category(category.connection, category.full_path, options)
end

.create_batch_without_category(connection, category_path, items, options = {}) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/amee/data_item.rb', line 148

def self.create_batch_without_category(connection, category_path, items, options = {})
  if connection.format == :json
    options.merge! :profileItems => items
    post_data = options.to_json
  else
  options.merge!({:DataItems => items})
  post_data = options.to_xml(:root => "DataCategory", :skip_types => true, :skip_nil => true)
  end
  # Post to category
  response = connection.raw_post(category_path, post_data).body
  # Send back a category object containing all the created items
  unless response.empty?
    return AMEE::Data::Category.parse(connection, response)
  else
    return true
  end
end

.create_without_category(connection, path, options = {}) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/amee/data_item.rb', line 170

def self.create_without_category(connection, path, options = {})
  # Do we want to automatically fetch the item afterwards?
  get_item = options.delete(:get_item)
  get_item = true if get_item.nil?
  # Store format if set
  format = options[:format]
  unless options.is_a?(Hash)
    raise AMEE::ArgumentError.new("Third argument must be a hash of options!")
  end
  # Create a data item!
  options[:newObjectType] = "DI"
  # Send data to path
  response = connection.post(path, options)
  if response['Location']
    location = response['Location'].match("https??://.*?(/.*)")[1]
  else
    category = Category.parse(connection, response.body)
    location = category.full_path + "/" + category.items[0][:path]
  end
  if get_item == true
    get_options = {}
    get_options[:format] = format if format
    return AMEE::Data::Item.get(connection, location, get_options)
  else
    return location
  end
rescue
  raise AMEE::BadData.new("Couldn't create DataItem. Check that your information is correct.\n#{response}")
end

.delete(connection, path) ⇒ Object



221
222
223
224
225
# File 'lib/amee/data_item.rb', line 221

def self.delete(connection, path)
  connection.delete(path)
rescue
  raise AMEE::BadData.new("Couldn't delete DataItem. Check that your information is correct.")
end

.from_json(json) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/amee/data_item.rb', line 34

def self.from_json(json)
  # Read JSON
  doc = JSON.parse(json)
  data = {}
  data[:uid] = doc['dataItem']['uid']
  data[:created] = DateTime.parse(doc['dataItem']['created'])
  data[:modified] = DateTime.parse(doc['dataItem']['modified'])
  data[:name] = doc['dataItem']['name']
  data[:path] = doc['path']
  data[:label] = doc['dataItem']['label']
  data[:item_definition] = doc['dataItem']['itemDefinition']['uid']
  data[:category_uid] = doc['dataItem']['dataCategory']['uid']
  # Read v2 total
  data[:total_amount] = doc['amount']['value'] rescue nil
  data[:total_amount_unit] = doc['amount']['unit'] rescue nil
  # Read v1 total
  if data[:total_amount].nil?
    data[:total_amount] = doc['amountPerMonth'] rescue nil
    data[:total_amount_unit] = "kg/month"
  end
  # Get values
  data[:values] = []
  doc['dataItem']['itemValues'].each do |value|
    value_data = {}
    value_data[:name] = value['name']
    value_data[:path] = value['path']
    value_data[:value] = value['value']
    value_data[:drill] = value['itemValueDefinition']['drillDown'] rescue nil
    value_data[:uid] = value['uid']
    data[:values] << value_data
  end
  # Get choices
  data[:choices] = []
  doc['userValueChoices']['choices'].each do |choice|
    choice_data = {}
    choice_data[:name] = choice['name']
    choice_data[:value] = choice['value']
    data[:choices] << choice_data
  end
  data[:start_date] = DateTime.parse(doc['dataItem']['startDate']) rescue nil
  # Create object
  Item.new(data)
rescue
  raise AMEE::BadData.new("Couldn't load DataItem from JSON. Check that your URL is correct.\n#{json}")
end

.from_xml(xml) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/amee/data_item.rb', line 80

def self.from_xml(xml)
  # Parse data from response into hash
  doc = REXML::Document.new(xml)
  data = {}
  data[:uid] = REXML::XPath.first(doc, "/Resources/DataItemResource/DataItem/@uid").to_s
  data[:created] = DateTime.parse(REXML::XPath.first(doc, "/Resources/DataItemResource/DataItem/@created").to_s)
  data[:modified] = DateTime.parse(REXML::XPath.first(doc, "/Resources/DataItemResource/DataItem/@modified").to_s)
  data[:name] = (REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/Name') || REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/name')).text
  data[:path] = (REXML::XPath.first(doc, '/Resources/DataItemResource/Path') || REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/path')).text
  data[:label] = (REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/Label') || REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/label')).text
  data[:item_definition] = REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/ItemDefinition/@uid').to_s
  data[:category_uid] = REXML::XPath.first(doc, '/Resources/DataItemResource/DataItem/DataCategory/@uid').to_s
  # Read v2 total
  data[:total_amount] = REXML::XPath.first(doc, '/Resources/DataItemResource/Amount').text.to_f rescue nil
  data[:total_amount_unit] = REXML::XPath.first(doc, '/Resources/DataItemResource/Amount/@unit').to_s rescue nil
  # Read v1 total
  if data[:total_amount].nil?
    data[:total_amount] = REXML::XPath.first(doc, '/Resources/DataItemResource/AmountPerMonth').text.to_f rescue nil
    data[:total_amount_unit] = "kg/month"
  end
  # Get values
  data[:values] = []
  REXML::XPath.each(doc, '/Resources/DataItemResource/DataItem/ItemValues/ItemValue') do |value|
    value_data = {}
    value_data[:name] = (value.elements['Name'] || value.elements['name']).text
    value_data[:path] = (value.elements['Path'] || value.elements['path']).text
    value_data[:value] = (value.elements['Value'] || value.elements['value']).text
    value_data[:drill] = value.elements['ItemValueDefinition'].elements['DrillDown'].text == "false" ? false : true rescue nil
    value_data[:uid] = value.attributes['uid'].to_s
    data[:values] << value_data
  end
  # Get choices
  data[:choices] = []
  REXML::XPath.each(doc, '/Resources/DataItemResource/Choices/Choices/Choice') do |choice|
    choice_data = {}
    choice_data[:name] = (choice.elements['Name']).text
    choice_data[:value] = (choice.elements['Value']).text || ""
    data[:choices] << choice_data
  end
  data[:start_date] = DateTime.parse(REXML::XPath.first(doc, "/Resources/DataItemResource/DataItem/StartDate").text) rescue nil
  # Create object
  Item.new(data)
rescue
  raise AMEE::BadData.new("Couldn't load DataItem from XML. Check that your URL is correct.\n#{xml}")
end

.get(connection, path, options = {}) ⇒ Object



127
128
129
130
131
132
133
# File 'lib/amee/data_item.rb', line 127

def self.get(connection, path, options = {})
  # Load data from path
  response = connection.get(path, options).body
  AMEE::Data::Item.parse(connection, response)
rescue
  raise AMEE::BadData.new("Couldn't load DataItem. Check that your URL is correct.\n#{response}")
end

.parse(connection, response) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/amee/data_item.rb', line 135

def self.parse(connection, response)
  # Parse data from response
  if response.is_json?
    item = Item.from_json(response)
  else
    item = Item.from_xml(response)
  end
  # Store connection in object for future use
  item.connection = connection
  # Done
  return item
end

.update(connection, path, options = {}) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/amee/data_item.rb', line 200

def self.update(connection, path, options = {})
  # Do we want to automatically fetch the item afterwards?
  get_item = options.delete(:get_item)
  get_item = true if get_item.nil?
  # Go
  response = connection.put(path, options)
  if get_item
    if response.body.empty?
      return Item.get(connection, path)
    else
      return Item.parse(connection, response.body)
    end
  end
rescue
  raise AMEE::BadData.new("Couldn't update DataItem. Check that your information is correct.\n#{response}")
end

Instance Method Details

#item_definitionObject



28
29
30
31
# File 'lib/amee/data_item.rb', line 28

def item_definition
  return nil unless item_definition_uid
  @item_definition ||= AMEE::Admin::ItemDefinition.load(connection,item_definition_uid)
end

#update(options = {}) ⇒ Object



217
218
219
# File 'lib/amee/data_item.rb', line 217

def update(options = {})
  AMEE::Data::Item.update(connection, full_path, options)
end

#value(name_or_path_or_uid) ⇒ Object



227
228
229
230
# File 'lib/amee/data_item.rb', line 227

def value(name_or_path_or_uid)
  val = values.find{ |x| x[:name] == name_or_path_or_uid || x[:path] == name_or_path_or_uid || x[:uid] == name_or_path_or_uid}
  val ? val[:value] : nil
end