I am making a framework where objects should be created a according to a predefined XML file.
For example, if in the xml file the following occurs:
<type name="man">
<property name="name" type="string">
<property name="height" type="int">
<property name="age" type="int">
<property name="profession" type="string" value="unemployed">
</type>
In Ruby, this should allow you to create an object as following:
man = Man.new('John', 188, 30)
Note: For fields where ‘value’ is defined in the xml, no value
should be accepted in the initialize method, but should rather be
set by the class itself as a default value.
Any recommended implementations for this?
I am current watching Dave Thomas’ screencasts about meta programming,
so this looks very suitable, but any suggestions would be appreciated!
Well, first you’ll need to parse the XML. You could use a library like Hpricot or Nokogiri for that. Here’s an example that will create a Man class given that type node from Nokogiri:
It’s not the most elegant bit of metaprogramming you’ll ever see, but I can’t think of how to make it any simpler at the moment. The first bit gets the class name and makes an empty class by that name, the second gets the attributes from the XML, and the third is the only real metaprogramming. It’s a class definition using that information (with the minor added hassle of needing to check the argument count, since we can’t tell Ruby “X number of arguments is required”).