Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > defining methods dynamically

Thread Tools

defining methods dynamically
Posts: n/a
On Nov 3, 2007 7:10 PM, brainopia <(E-Mail Removed)> wrote:
> > Exactly that was why I thaught of delegation, as I am not familiar
> > with the delegation idioms please forgive me that I handcoded it
> >
> > class Person
> > @roles = %w{ a b c d }
> > class << self; attr_reader :roles end
> > def method_missing name,*args,&blk
> > super unless name
> > ### do delegation here
> > @some_obj.send name, *args, &blk
> > end

> method_missing - is awfully slow, so if there is other option (like two
> from Dan Yoder) than better to use them at the cost of a few more lines.

I was showing the concept and I asked to imagine that delegation was
used, did I not?
However I do not think that the speed of method missing might be an
issue and dynamic delegation would probably be slow too.
Now if speed really is an issue you could of course do something like
the following
class DynamicDefiners
def initialize klass
@klass = klass
@names = [] # not used in this simple usecase
def add *names
@names += names
names.each do | name |
@klass.module_eval do
attr_accessor name # or more sophisticated stuff as defining delegators
def del *names
@names -= names
names.each do | name |
@klass.module_eval do
remove_method name # or more sophisticated stuff as deleting delegators

class Person
@roles = self
@roles.add *%w{ foo bar }
class << self; attr_reader :roles end
def initialize
@foo = 22
@bar = 32
@baz = 42

p =
puts( )
puts( ) rescue puts "no bar"
puts( p.baz ) rescue puts "no baz"

Person.roles.add "baz"
Person.roles.del "bar"

puts( )
puts( ) rescue puts "no bar"
puts( p.baz ) rescue puts "no baz"

I do not think one would need this stuff but who knows

what do I think about Ruby?

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Is there a way to find the class methods of a class, just like'methods' finds the instance methods? Kenneth McDonald Ruby 5 09-26-2008 03:09 PM
Followup question on defining methods dynamically Kenneth McDonald Ruby 5 08-04-2007 11:01 PM
defining methods dynamically? Kenneth McDonald Ruby 5 08-03-2007 05:03 AM
Defining methods outside of script tags Jasper Pearlman ASP .Net 3 08-16-2004 12:26 PM
defining or not defining destructors johny smith C++ 8 07-02-2004 08:51 AM