hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Tuesday

2005.03.29

Eval-less Metaprogramming #

by why in bits

I often find myself resorting to eval when writing class methods for metaprogramming, simply because define_method hasn’t penetrated my brain basket yet. No more!

Here goes Florian GroBB changing Ruby as I know it—yet again—with his implementation of an eval-less has_many class method:

 class Meta
   def self.has_many( sym )
     ivar = :"@#{ sym }" 
     define_method( sym.to_sym ) do
       new_value = instance_variable_get( ivar ) || []
       instance_variable_set( ivar, new_value )
       new_value
     end
   end
 end

Even though has_many is a sorta poor name (we’re not talking about databases here), this method acts like an attr method, but the attribute is always an Array.

 class Person < Meta
   attr_accessor :name
   has_many :friends
   def initialize( name ); @name = name; end
 end

 >> fred = Person.new( "Fred" )
 >> joe = Person.new( "Joe" )
 >> teagle = Person.new( "T. Eagle" )
 >> teagle.friends << fred
 >> teagle.friends << joe
 => [#<Person:0x80f3ebc @name="Fred">, #<Person:0x81fd404 @name="Joe">]

Let Three Weeks of Unhindered Ruby Learning Begin! #

by why in cult

If you’re completely new to Ruby—maybe you haven’t even seen a single scrap of Ruby code, maybe you don’t know what it is at all—you are invited to join Al Abut on his three-week blogging escapade to learn Ruby, which began yesterday and will go through April 9th. But yesterday was just a summary, so you’re okay to start today. He’s summarizing chapters of Mark Slagell’s Teach Yourself Ruby in 21 Days.

But, yeah. Follow the RSS for three weeks and you’re passively reading the whole book. A good deal.