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 inherited from Object

#expire_cache, get_and_parse

Methods included from ParseHelper

#load_xml_doc, #node_value, #xmlpathpreamble

Constructor Details

#initialize(data = {}) ⇒ Item

Returns a new instance of Item.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/amee/data_item.rb', line 10

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.



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

def category_uid
  @category_uid
end

#choicesObject (readonly)

Returns the value of attribute choices.



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

def choices
  @choices
end

#item_definition_uidObject (readonly)

Returns the value of attribute item_definition_uid.



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

def item_definition_uid
  @item_definition_uid
end

#labelObject (readonly)

Returns the value of attribute label.



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

def label
  @label
end

#start_dateObject (readonly)

Returns the value of attribute start_date.



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

def start_date
  @start_date
end

#total_amountObject (readonly)

Returns the value of attribute total_amount.



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

def total_amount
  @total_amount
end

#total_amount_unitObject (readonly)

Returns the value of attribute total_amount_unit.



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

def total_amount_unit
  @total_amount_unit
end

#valuesObject (readonly)

Returns the value of attribute values.



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

def values
  @values
end

Class Method Details

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



174
175
176
# File 'lib/amee/data_item.rb', line 174

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



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/amee/data_item.rb', line 156

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



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/amee/data_item.rb', line 178

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



229
230
231
232
233
# File 'lib/amee/data_item.rb', line 229

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



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
79
80
81
82
83
# File 'lib/amee/data_item.rb', line 37

def self.from_json(json)
  # Read JSON
  doc = JSON.parse(json)
  begin
    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
end

.from_xml(xml) ⇒ Object



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
125
126
127
128
129
130
131
# File 'lib/amee/data_item.rb', line 85

def self.from_xml(xml)
  # Parse data from response into hash
  doc = REXML::Document.new(xml)
  begin
    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
end

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



134
135
136
137
138
139
140
141
# File 'lib/amee/data_item.rb', line 134

def self.get(connection, path, options = {})
  # Load data from path
  item= get_and_parse(connection, path, options)
  # Store connection in object for future use
  item.connection = connection
  # Done
  return item
end

.parse(connection, response) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/amee/data_item.rb', line 143

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



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/amee/data_item.rb', line 208

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



31
32
33
34
# File 'lib/amee/data_item.rb', line 31

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

#update(options = {}) ⇒ Object



225
226
227
# File 'lib/amee/data_item.rb', line 225

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

#value(name_or_path_or_uid) ⇒ Object



235
236
237
238
# File 'lib/amee/data_item.rb', line 235

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