Reputation: 600
Say I have function with_foo
that takes a block, and wrap it around a piece of code, like
with_foo do
puts "hello!"
end
Now I would like to make the wrapping conditional, like
if do_with_foo?
with_foo do
puts "hello!"
end
else
puts "hello!" # without foo
end
Is there any way to write this shorter/more elegantly, meaning without having to repeat the code puts "hello!"
?
Upvotes: 11
Views: 6655
Reputation: 67850
A proof of concept using the proxy pattern:
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
Output:
with_foo: start
hello!
with_foo: end
hello, no with_foo here!
Upvotes: 4
Reputation: 20408
def simple_yielder
yield
end
def maybe_with condition, with_method
send( condition ? with_method : :simple_yielder ) { yield }
end
#...
maybe_with( do_with_foo?, :with_foo ) do
puts "Hello?"
end
Upvotes: 2
Reputation: 168081
I think you can do this:
def without_foo &pr
pr.call
end
send(do_with_foo?? "with_foo" : "without_foo") do
puts "hello!"
end
Upvotes: 2
Reputation: 5617
if you are willing to specify argument with a block, it is possible.
given with foo
above, you can write such snippet:
whatever = proc {puts "hello"}
#build a proc object with a block
if do_with_foo?
with_foo &whatever
#pass it to with_foo
else
whatever.call
#normally call it
end
Upvotes: 9
Reputation: 4245
You can put the duplication code into Proc
object and pass it to the method as block or call it directly.
hello = proc { puts 'hello' }
with_foo(&hello)
# OR
hello.call
Upvotes: 4