Class: CIMI::Model::Schema::Collection

Inherits:
Attribute
  • Object
show all
Defined in:
lib/cimi/models/schema.rb

Instance Attribute Summary

Attributes inherited from Attribute

#json_name, #name, #xml_name

Instance Method Summary collapse

Constructor Details

#initialize(name, opts = {}) ⇒ Collection

Returns a new instance of Collection.



220
221
222
223
224
225
226
227
228
229
# File 'lib/cimi/models/schema.rb', line 220

def initialize(name, opts = {})
  params = {}
  params[:scope] = opts.delete(:scope)
  super(name, opts)
  unless opts[:class]
    raise "Specify the class of collection entries using :class"
  end
  params[:embedded] = true
  @collection_class = CIMI::Model::Collection.generate(opts[:class], params)
end

Instance Method Details

#convert(value) ⇒ Object

Convert a Hash or Array to an instance of the collection class



262
263
264
265
266
267
268
# File 'lib/cimi/models/schema.rb', line 262

def convert(value)
  if value.is_a?(::Array)
    @collection_class.new(:entries => value)
  else
    @collection_class.new(value || {})
  end
end

#from_json(json, model) ⇒ Object



237
238
239
240
241
# File 'lib/cimi/models/schema.rb', line 237

def from_json(json, model)
  if json[json_name]
    model[name] = @collection_class.schema.from_json(json[json_name], {})
  end
end

#from_xml(xml, model) ⇒ Object



231
232
233
234
235
# File 'lib/cimi/models/schema.rb', line 231

def from_xml(xml, model)
  if xml[xml_name]
    model[name] = @collection_class.schema.from_xml(xml[xml_name].first, {})
  end
end

#to_json(model, json) ⇒ Object



252
253
254
255
256
257
258
259
# File 'lib/cimi/models/schema.rb', line 252

def to_json(model, json)
  model[name].prepare
  if model[name].entries.empty?
    json[json_name] = { "href" => model[name].href }
  else
    json[json_name] = @collection_class.schema.to_json(model[name])
  end
end

#to_xml(model, xml) ⇒ Object



243
244
245
246
247
248
249
250
# File 'lib/cimi/models/schema.rb', line 243

def to_xml(model, xml)
  model[name].prepare
  if model[name].entries.empty?
    xml[xml_name] = { "href" => model[name].href }
  else
    xml[xml_name] = @collection_class.schema.to_xml(model[name])
  end
end