The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Eval-less Metaprogramming

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
Eval-less Metaprogramming Posted: Mar 30, 2005 10:28 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Red Handed.
Original Post: Eval-less Metaprogramming
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

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
 => [#, #]

Read: Eval-less Metaprogramming

Topic: When documentation lies Previous Topic   Next Topic Topic: 9412

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use