Created
January 15, 2011 01:29
-
-
Save dmichael/780599 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ROXML | |
| class XMLHashRef | |
| def update_hash(hash, instance) | |
| raise "not implemented" | |
| end | |
| end | |
| class XMLAttributeRef | |
| def update_hash(hash, instance) | |
| ap self.class | |
| ap instance.class | |
| hash[self.accessor] = instance.send(self.accessor) | |
| hash | |
| end | |
| end | |
| class XMLTextRef | |
| def update_hash(hash, instance) | |
| hash[self.accessor] = instance.send(self.accessor) | |
| hash | |
| end | |
| end | |
| class XMLObjectRef | |
| def update_hash(hash, instance) | |
| # ap self.class | |
| # ap instance.class | |
| value = instance.send(self.accessor) | |
| hash[accessor] = | |
| case value | |
| when Array | |
| value.inject([]) {|array, v| | |
| array << | |
| if v.is_a?(ROXML) | |
| v.to_hash | |
| else | |
| v.update_hash(hash, instance) | |
| end | |
| } | |
| when ROXML then value.to_hash | |
| else value | |
| end | |
| hash | |
| end | |
| end | |
| module InstanceMethods | |
| def to_hash(params = {}) | |
| ap "#{self.class}#to_hash" | |
| root = {} | |
| refs = (self.roxml_references.present? ? self.roxml_references : self.class.roxml_attrs.map {|attr| attr.to_ref(self) }) | |
| refs.each do |ref| | |
| ref.update_hash(root, self)# unless value.nil? | |
| end | |
| return root | |
| end | |
| end | |
| module ClassMethods | |
| module Operations | |
| def from_hash(hash) | |
| instance = self.new | |
| hash.each do |key, value| | |
| key_definition = self.roxml_attrs.find {|attr| attr.accessor == key} | |
| type = key_definition.sought_type | |
| puts "Invalid key #{key}" && next unless key_definition | |
| next if value.nil? | |
| if key_definition.array? | |
| puts "Type #{value.class} is not an array, but one was defined" and next unless value.is_a?(Array) | |
| value = value.inject([]) {|array, v| | |
| array << ((type.respond_to?(:roxml_attrs)) ? type.from_hash(v) : v) | |
| } | |
| else | |
| value = ((type.respond_to?(:roxml_attrs)) ? type.from_hash(value) : value) | |
| end | |
| instance.send("#{key}=", value) | |
| end | |
| # now return the instance we just build up | |
| return instance | |
| end | |
| # from_hash | |
| end | |
| end | |
| # ClassMethods | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment