Pass Yer Blocks When Auto-Proxying in Ruby
posted
Friday, June 27 at 03:55AM
Originally posted January 09, 2008 at masonbrowne.info:
I was working on a bit of code with an auto-proxy (via method_missing). It was something like this (very simplified here):
class Engine
attr_accessor :processor
# ...
def method_missing(meth, *args)
@processor.send(meth, *args)
end
end
class Processor
attr_accessor :infile, :outfile
# ...
def process
yield(self) if block_given?
# ...
# raises error if @infile and @outfile aren't set anywhere
end
end
@engine = Engine.new(:engine_type, :processor_type)
@engine.process do |proc|
proc.infile = "path/to/infile"
proc.outfile = "path/to/outfile"
end
But, that wasn't working. And it wasn't working, because my proxy wasn't forwarding my block. So:
class Engine
attr_accessor :processor
# ...
def method_missing(meth, *args, &block)
@processor.send(meth, *args, &block)
end
end
And, as if by magic, my unit tests pass.