SOAP in Ruby with Hpricot (a better way)

Ok, after a bit a comment war on the previous port (SOAP4R with Hpricot) I feel the need to present a better way of dealing with XML pass-through using Hpricot. This is why Ruby is such a powerful language.

So, let’s say we have and object. Any object in Ruby has “class” method, which in turn has “class_eval” method. Passing a code block to it is equivalent of adding things into the class itself. No “to_xmlpart” method? No problem! Behold:


require 'hpricot'

xml_doc = Hpricot::XML(File.read("MyXML.xml"))
xml_doc.class.class_eval do
   def to_xmlpart
      self.to_html
   end
end
puts xml_doc.to_xmlpart

Boom! Hpricot::Doc object suddenly has “to_xmlpart” method. Now you can pass it into any SOAP RPC method and it won’t try to muck with it. That my friends is the Ruby Way.

P.S. I hate you Scott. Curse you for not letting me half-ass things. :)

Leave a Reply