プロキシパターンを使用した概念実証:
class BlockWrapper
def initialize(obj, use_wrapper)
@obj = obj
@use_wrapper = use_wrapper
end
def method_missing(*args, &block)
@use_wrapper ? @obj.send(*args, &block) : block.call
end
end
module Kernel
def wrap_if(use_wrapper)
BlockWrapper.new(self, use_wrapper)
end
end
def with_foo
puts "with_foo: start"
yield
puts "with_foo: end"
end
wrap_if(true).with_foo do
puts "hello!"
end
wrap_if(false).with_foo do
puts "hello, no with_foo here!"
end
出力:
with_foo: start
hello!
with_foo: end
hello, no with_foo here!