C
Christoffer Lernö
For example, something that I often want to do is:
array.each { |entry| entry.do_something(1, "a") }
If you know you're doing things like this a lot, there is an obvious
shortcut:
class Array
class Forwarder
def initialize(array)
@array = array
end
def method_missing(symbol, *args)
@array.each { |entry| entry.__send__(symbol, *args) }
end
end
def each_do
Forwarder.new(self)
end
end
Now you can do:
array.each_do.do_something(1, "a")
In a more generalized case, you want to use a block to act as a class.
module Trampolines
class Trampoline
def initialize(block)
@block = block
end
def method_missing(symbol, *args, &block)
args << block if block
@block.call(symbol, *args)
end
end
end
def trampoline(&block)
raise "Missing block" unless block
Trampolines::Trampoline.new(block)
end
Here we could define
class Array
def each_do2
trampoline { |symbol, *args| each { |o| o.__send__(symbol,
*args) } }
end
end
Which would work the same way as the previous code.
But you could also do things like
def wait(time)
trampoline do |method, *args|
# queue_event executes the block after time seconds
queue_event(time) { self.__send__(method, *args) }
end
end
And write code like:
wait(5).shutdown("Shutdown in seconds")
wait(10).shutdown("Shutdown in 5 seconds")
wait(15).shutdown_now
Instead of wrapping it in blocks.
Other people must have played around with this.
I'd like to learn more about using these methods, so are there any
links and sites people could share with me?
/Christoffer
array.each { |entry| entry.do_something(1, "a") }
If you know you're doing things like this a lot, there is an obvious
shortcut:
class Array
class Forwarder
def initialize(array)
@array = array
end
def method_missing(symbol, *args)
@array.each { |entry| entry.__send__(symbol, *args) }
end
end
def each_do
Forwarder.new(self)
end
end
Now you can do:
array.each_do.do_something(1, "a")
In a more generalized case, you want to use a block to act as a class.
module Trampolines
class Trampoline
def initialize(block)
@block = block
end
def method_missing(symbol, *args, &block)
args << block if block
@block.call(symbol, *args)
end
end
end
def trampoline(&block)
raise "Missing block" unless block
Trampolines::Trampoline.new(block)
end
Here we could define
class Array
def each_do2
trampoline { |symbol, *args| each { |o| o.__send__(symbol,
*args) } }
end
end
Which would work the same way as the previous code.
But you could also do things like
def wait(time)
trampoline do |method, *args|
# queue_event executes the block after time seconds
queue_event(time) { self.__send__(method, *args) }
end
end
And write code like:
wait(5).shutdown("Shutdown in seconds")
wait(10).shutdown("Shutdown in 5 seconds")
wait(15).shutdown_now
Instead of wrapping it in blocks.
Other people must have played around with this.
I'd like to learn more about using these methods, so are there any
links and sites people could share with me?
/Christoffer