David McCabe wrote:
> In python, my parser returns a hash of unit_type objects, where the
> names of units are the keys. Each time a unit is instantiated, it
> receives a unit_type object as an argument. Now here's the
interesting
> part: it copies the instance variables from the unit_type into
itself.
>
> class Unit(object):
>       def __init__(self, type):
> 	  self.type = type
> 	  self.__dict__.update(self.type.__dict__)
>
> There's more to it than that, but that's the interesting part. So now
> I can say:
>
>       my_new_unit = Unit(types["Panzer"])
>
> And I'll get a Unit object with all the values for Panzers
> initialized.
>
> drbrain on #ruby-lang came up with this:
>
> http://rafb.net/paste/results/lgb4xv42.html
>
> It looks like it'll do what I want. There's only one deficiency: I
> would have to list out every possible proporty of a unit in two
> seperate places in the source. In the python version, I don't have to
> list it at all. Whatever properties are in the config file are loaded
> into the object.
>
> So, now I'm looking for any pointers on ways to do this.

Suppose you have a hash of properties like this:
.. h = { :range => 100, :strength => 50 }

Then you can define at run time accessors for these properties and set
their values like this:
.. class Unit
..   def initialize properties
..     properties.each { |k, v|
..       # define accessor
..       singleton_class.send :attr_accessor, k
..       # initialize with value
..       self.instance_variable_set "@#{k}", v
..     }
..   end
.. end

Test with:
.. a = Unit.new h
.. puts a.range

You don't have to crate the accessors, but ruby treats all instance
variables as private. So unless you define them, you will not be able
to see them from outside the instance.


The #singleton_class method is a convenient shortcut, defined as:
.. class Object
..   def singleton_class
..     class << self; self; end
..   end
.. end


HTH,
Assaph