Design for Ruby app using meta programming -


I am creating an outline where the objects should be created according to a predefined XML file. For example, if the XML file The following happens:

  & lt; Type name = "man" & gt; & Lt; Property name = "name" type = "string" & gt; & Lt; Property name = "height" type = "int" & gt; & Lt; Property name = "age" type = "int" & gt; & Lt; Property name = "business" type = "string" value = "unemployed" & gt; & Lt; / Type & gt;  

In Ruby, you should allow to create an object as: Man New )

Note: For values ​​where 'value' is defined in XML, no value should be accepted in the initial method, rather It should be determined by the class as a default value.

Any recommended implementation for this? I'm watching Dave Thomas's screencast about meta programming, so it looks very suitable, but any suggestions would be appreciated!

OK, first you have to parse the XML. You can use the library such as HPricot or Nougery for this. Here is an example that will create a nickname from nogogiri to the type node:

def define_class_from_xml (node, in_module = object) class_name = node ['name']. Dup class_name [0] = Class_name [0] .upcase new_class = in_module.const_set (class_name, class.new) attribute = node.search ('property'). Map {| Child | Child ['name']} attribute_mysn = node Search ('property [[original value]'). Do inject ({}). Hash, baby Hash [child ['name']] = children ['value'] hash terminate new_class.class_eval do attr_accessor * attributes define_method (: initialize). * Args | Need_args_count = attributes.size - attribute_values.size if args.size & lt; Increase required_ args_count ArgumentError, "# {args.size} given arguments given; # {needed_args_count} required" end attributes.zip (args) .each {| Attr, val | "# {Attr} =", val} if args.size & lt; Attributes.size attributes [args.size ..- 1] .each {| Attr | "# {Attr} =", attribute_type [atri], end end and end

You can never send the most elegant bit of metaprogramming, but I can not think this time How to make any simple, the first bit gets the name of the class and makes that name an empty square, the other gets the properties of XML, and the third is the only real metaprogramming it using that information. Las definition (with the slight added difficulty of needing to examine the case number, because we have essential argument of "X can not tell Ruby").


Comments

Popular posts from this blog

c++ - Linux and clipboard -

Visual Studio 2005: How to speed up builds when a VSMDI is open? -

booting ubuntu from usb using virtualbox -