Commit e68a85969383321b4cf557bf645528a5b2c74aa4
Committed by
Paulo Meireles
1 parent
da079692
Exists in
master
and in
22 other branches
[Mezuro] Added Kalibro::Model file
Showing
1 changed file
with
41 additions
and
0 deletions
Show diff stats
| ... | ... | @@ -0,0 +1,41 @@ |
| 1 | +class Kalibro::Model | |
| 2 | + | |
| 3 | + def initialize(attributes={}) | |
| 4 | + attributes.each { |field, value| send("#{field}=", value) } | |
| 5 | + end | |
| 6 | + | |
| 7 | + def to_hash | |
| 8 | + hash = Hash.new | |
| 9 | + fields.each do |field| | |
| 10 | + field_value = send(field) | |
| 11 | + hash[field] = convert_to_hash(field_value) | |
| 12 | + if field_value.is_a?(Kalibro::Model) | |
| 13 | + hash = {:attributes! => {}}.merge(hash) | |
| 14 | + hash[:attributes!][field.to_sym] = { | |
| 15 | + 'xmlns:xsi'=> 'http://www.w3.org/2001/XMLSchema-instance', | |
| 16 | + 'xsi:type' => 'kalibro:' + xml_class_name(field_value) } | |
| 17 | + end | |
| 18 | + end | |
| 19 | + hash | |
| 20 | + end | |
| 21 | + | |
| 22 | + protected | |
| 23 | + | |
| 24 | + def fields | |
| 25 | + instance_variable_names.each.collect { |variable| variable.to_s.sub(/@/, '').to_sym } | |
| 26 | + end | |
| 27 | + | |
| 28 | + def convert_to_hash(value) | |
| 29 | + return value if value.nil? | |
| 30 | + return value.to_hash if value.is_a?(Kalibro::Model) | |
| 31 | + value | |
| 32 | + end | |
| 33 | + | |
| 34 | + def xml_class_name(entity) | |
| 35 | + xml_name = entity.class.name | |
| 36 | + xml_name["Kalibro::"] = "" | |
| 37 | + xml_name[0..0] = xml_name[0..0].downcase | |
| 38 | + xml_name + "Xml" | |
| 39 | + end | |
| 40 | + | |
| 41 | +end | ... | ... |