Dynamic methods

J

-j B-

I have seen examples of catching unkown methods called on a class with
method_missing.
For example:

class Example
def initialize(...)
#...
end

def method_missing(item)
call = item.id2name
process(call)
end
end

But I'm not sure if that is an 'acceptable' way to do things. Also,
suppose that I wanted to add a method dynamically that takes arguments,
is this even possible?
My general thought is allowing functionality to be added to a program
dynamically based on a set of rules in a config file.
Any suggestions are welcome.
Thank you.
 
T

Trans

I have seen examples of catching unkown methods called on a class with
method_missing.
For example:

class Example
def initialize(...)
#...
end

def method_missing(item)
call = item.id2name
process(call)
end

def method_missing(item, *args, &blk)
process(item, *args, &blk) # item is already a symbol
end
end

But I'm not sure if that is an 'acceptable' way to do things. Also,
suppose that I wanted to add a method dynamically that takes arguments,
is this even possible?
My general thought is allowing functionality to be added to a program
dynamically based on a set of rules in a config file.
Any suggestions are welcome.
Thank you.

Also, keep in mind Ruby classes are open. You can add real methods to
them on the fly.

class Example
end

foo = "bar"

Example.class_eval %{
def #{foo}
"#{foo}"
end
}

Example.new.foo #=> "bar"

T.
 
M

Marcin Mielżyński

Trans said:
Also, keep in mind Ruby classes are open. You can add real methods to
them on the fly.

class Example
end

foo = "bar"

Example.class_eval %{
def #{foo}
"#{foo}"
end
}

It's better not to use string evals:

Example.class_eval do
define_method foo do
"#{foo}"
end
end

lopex
 
R

Robert Dober

class A
class << self
alias_method :eek:ld_new, :new
def new *args, &block
o = old_new( *args, &block )
o.instance_eval do
def ara; value end
end
o
end
end
end ## this does the trick, simple concise, trivial :( well we wish it were.
## and there are issues with the alias it is a potential redefeinition disaster
the above really su..., sorry

class A
alias_method :eek:ld_init, :initialize
def initialize *args, &blk
old_init( *args, &blk )
instance_eval do
def ara; value end
end
end
end
# the issues remain though, we could apply the method redefintion
hammer Pit and Ara came up with and just redefine initialize like
that, but that would make it about 100 lines I guess :(

Robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top