Created
September 17, 2013 09:42
-
-
Save hawx/6592213 to your computer and use it in GitHub Desktop.
Idea for deserialising xml to ruby objects.
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
require 'nokogiri' | |
module Deserialisable | |
def root(selector) | |
@__root = selector | |
@__elements = {} | |
end | |
def element(name, selector, type=String) | |
@__elements[name] = [selector, type] | |
end | |
def from_xml(data) | |
doc = Nokogiri::XML(data).css(@__root) | |
attrs = @__elements.map {|name, (selector, type)| | |
value = doc.css(selector).children.to_s | |
if type.respond_to?(:parse) | |
value = type.parse(value) | |
end | |
[name, value] | |
} | |
attrs = Hash[attrs] | |
attrs.each do |key, value| | |
define_method key do | |
instance_variable_get(:@attrs)[key] | |
end | |
end | |
obj = new | |
obj.instance_variable_set(:@attrs, attrs) | |
obj | |
end | |
end |
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
require_relative 'deserialisable' | |
require 'time' | |
class MessageFailed | |
extend Deserialisable | |
root 'MessageFailed' | |
element :id, 'Id' | |
element :message_id, 'MessageId' | |
element :account_id, 'AccountId' | |
element :occurred_at, 'OccurredAt', Time | |
end | |
f = MessageFailed.from_xml <<EOS | |
<MessageFailed> | |
<Id>04f5f181-81eb-44f2-8ccd-e01fcc7077e3</Id> | |
<MessageId>4769ab2c-708a-4b7e-8951-587c5e907a35</MessageId> | |
<AccountId>45790956-44aa-412c-a4fa-8c7555c64968</AccountId> | |
<OccurredAt>2013-08-04T12:00:05Z</OccurredAt> | |
</MessageFailed> | |
EOS | |
p f.occurred_at | |
#=> 2013-08-04 12:00:05 UTC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment