Recursive method definition -- A Metaprogramming problem??

D

DMisener

Any hints on how to imbed *redefine_method*'s *payload* as a block
instead of a *nasty" eval string?
(see example below)


# How support payload being a block??
def redefine_method method,payload # using previous definition of
itself
class_eval %[
alias old_#{method} #{method}
def #{method}(*args,&block)
alias new_#{method} #{method}
def #{method}(*args,&block); old_#{method}(*args,&block)
end
#{payload}
def #{method}(*args,&block); new_#{method}(*args,&block)
end
end
]
end

This is useful when redefining a new method using existing code which
uses the "prior" definition's implementation.

Example usage:

class FS_TransactionsFile < PA_TransactionsFile
redefine_method :each,%[filter(proc{|_| %w[LW KS].member? _.fcode})
{|_| yield _}]
end

where FS_TransactionFile implements the *filter* method using a
possibly similarly redefined definition of *each* (for
PA_TransactionFile).

The above works -- but seems clumsy.

FYI: Filter in above example is currently implemented as:

class Object # combination of Select/Map functionality
def filter owncode=nil,keep_original=true
# *keep_original* is the content value used to mean return the
original item
# i.e. if keep_original=true and the select routine returns
true then
# the original value will be added to result/yielded.
owncode||=proc{|_| _} # default mapping is 'identity' i.e.
same as find_all
result=[] # used to collect resulting items if block not
given
each do |item|
if _=owncode.call(item) # nil items are discarded
_=item if _==keep_original
if block_given?
yield _
else
result << _
end
end
end
result
end
end
 

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,770
Messages
2,569,584
Members
45,078
Latest member
MakersCBDBlood

Latest Threads

Top