Quote: Is a person who blows up banks an econoclast?
(Courtesy of fortune cookies)

Welcome to the Cool Spot of the Sun

Background: YAML is a very simple markup language which is more versatile than XML in representing complex objects. I first encountered problems using XML when I needed to represent a 'tree' Datastructure in the shortest way possible. Fortunately I found YAML.

Problem:  I want to read and write an Object in Ruby using YAML. 

Difficulty Level: Beginner 

Solution: In Ruby each object has a 'super' method called as to_yaml. Super methods are methods that are inherited from the parent class. 

     to_yaml can be used with any object to convert to YAML 

Add a method inside the class that will write to a file

     def writeObject(yamlfile)
        ys=File.open(yamlfile,"w")
        ys<<to_yaml;
        ys.close
     end

Above we are justopening a file and writing the content. Simple. 

Once that is done, let's now read the object from the file:

      def readObject(yamlfile)
         logg = YAML::load(File.open(yamlfile))
         copycon(logg)
         print "Values loaded from #{yamlfile}\n"
      end

logg is the loaded object which can then be used to populate the current object. In my case its done by the method copycon. The method copycon is like the copy constructor method of C . If for example our class had variables "name" and "id" than the copycon method would look like:

      def copycon(temp)
          name=temp.name

          id=temp.id

      end

Changing the defaults: 

If the contents of the YAML file are examined, than one can see the object is mentioned as ---!ruby/Object

This can be changed on overloading 2 functions in the class.

   def to_yaml_type
    "!Name,2006/Parameters"
  end  

  def register_YAML
    YAML.add_domain_type( "Name,2006", "Parameters" ) { |type, val|
     YAML.object_maker( Simulation, val )
    }
  end

You need to call up register_YAML before writing to the file or using the to_yaml method. The simplest way is to put an entry into initialize. As you can see the overloaded method specification is pretty simple. Be wary to put an ! in the string in to_yaml_type. More information on what these methods mean can be found in the references.

Do note that one can use different types of objects within the same YAML file. For example, Objects containing objects of other classes and so on.

Caveat: As a reference to an Object does'nt refer to an real Object when written to in YAML(program exited and restarted), be careful when storing such an Object. The best bet is to store strings and numericals and re-construct the object heirarchy after loading.

References:  YAML-Ruby at Sourceforge   



Get Firefox!  Use OpenOffice.org lastRSS.php - RSS parser for PHP Valid HTML 4.01! Valid CSS! IP Address Lookup


The visitor number 13195
Disclaimer