views:

42

answers:

1

I've been using WCF's DataContract and DataContractSerializer to read/write objects to XML files. We want to switch to using a Ruby on Rails version, and I wanted to find out what I could use. We have objects that have attributes like (these are just examples not the exact objects):

[DataContract]
public class City
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Location { get; set; }
}

[DataContract]
public class Person
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public City Home {get; set; }

    // returns true if the city is near me
    public bool NearMe(City myCity) { // insert code to compare cities }
}

and the code to read in the objects is:

DataContractSerializer ds = new DataContractSerializer(typeof(Person));
using (Stream s = File.OpenRead("person1.xml"))
{
     Person p = (Person) ds.ReadObject(s);
}

What is the equivalent format for doing the same thing in Ruby/Rails? How do I define the objects? What method do I read them in from an XML file? I've seen that I can try to define everything as a Model and then create a backend DB for each object. Is there anyway to do it without creating all the db tables, since we do not need a db for this application, but are just reading in a static set of the objects from the XML files.

A: 

If you need to support the xml schema that's coming from WCF and you don't need to have a database backing your application you could look at happy mapper:

http://railstips.org/blog/archives/2008/11/17/happymapper-making-xml-fun-again/

It's a great way to serialize to and from xml in ruby.

Your example would be something like:

class City
  include HappyMapper
  element :name, :tag => "Name"
  element :location, :tag => "Location"
end 

class Person
  include HappyMapper
  element :name, :tag => "Name"
  has_one :city, :tag => "City"
end

You would then parse the xml by doing:

people = Person.parse(xml_string)
people.each do |person|
  puts person.name
end

I hope this helps...

jonnii