Class: CIMI::Model::Schema::Hash

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

Instance Attribute Summary

Attributes inherited from Attribute

#json_name, #name, #required, #xml_name

Instance Method Summary collapse

Methods inherited from Attribute

#convert, #required?, #valid?

Constructor Details

#initialize(name, opts = {}, &block) ⇒ Hash

Returns a new instance of Hash.


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

def initialize(name, opts = {}, &block)
  opts[:json_name] = name.to_s.pluralize unless opts[:json_name]
  super(name, opts)
end

Instance Method Details

#from_json(json, model) ⇒ Object


274
275
276
# File 'lib/cimi/models/schema.rb', line 274

def from_json(json, model)
  model[name] = json[json_name] || {}
end

#from_xml(xml, model) ⇒ Object


267
268
269
270
271
272
# File 'lib/cimi/models/schema.rb', line 267

def from_xml(xml, model)
  model[name] = (xml[xml_name] || []).inject({}) do |result, item|
    result[item["key"]] = item["content"]
    result
  end
end

#to_json(model, json) ⇒ Object


283
284
285
286
# File 'lib/cimi/models/schema.rb', line 283

def to_json(model, json)
  h = extract(model)
  json[json_name] = h unless h.empty?
end

#to_xml(model, xml) ⇒ Object


278
279
280
281
# File 'lib/cimi/models/schema.rb', line 278

def to_xml(model, xml)
  mapped = extract(model).map { |k, v| { "key" => k, "content" => v } }
  xml[xml_name] = mapped unless mapped.empty?
end