Posts Tagged ‘hash’

Easy Hash to XML and back conversion in Ruby

Wednesday, October 8th, 2008

Instead of spending hours trying to write something custom to convert your hash into xml or vice versa, you can do it in one line. If you are already in a Rails environment, you are good to go, but if using ruby, include the ActiveSupport gem:

require 'rubygems'
require 'active_support'

Now that you have, we can convert a xml to a hash:

hash = Hash.from_xml(xml_stream)

And a hash to xml is stupid simple:

xml = hash.to_xml

There you have it, simple xml to hash and hash to xml!

ActiveRecord conditions with association from hash

Friday, August 29th, 2008

I’m sure you all know how to use the :conditions attribute when using ActiveRecord:

User.find(:all, :conditions=>['active = ?', true])

And you may even use associations this way:

User.find(:all, :include=>[:photos], :conditions=>['photos.removed = ? and users.active = ?', false, true])

But did you know that you can do this easier through hashes?

User.find(:all, :conditions=>{:active=>true})
User.find(:all, :include=>[:photos], :conditions=>{'photos.removed'=>false, 'users.active'=>true})

Nothing special there, but I thought it was pretty cool. One thing you have to remember when using associations, is to include that model.