Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and re-use block for method calls

Tags:

ruby

I am calling the RestClient::Resource#get(additional_headers = {}, &block) method multiple times with the same block but on different Resources, I was wondering if there is a way to save the block into a variable, or to save it into a Proc convert it into a block each time.

Edit:

I did the following:

resource = RestClient::Resource.new('https://foo.com')
redirect  =  lambda do  |response, request, result, &block|
  if [301, 302, 307].include? response.code
     response.follow_redirection(request, result, &block)
   else
      response.return!(request, result, &block)
   end
end
@resp = resource.get (&redirect)

I get: Syntax error, unexpected tAMPER

like image 964
Mouhyi Avatar asked May 25 '12 16:05

Mouhyi


1 Answers

foo = lambda do |a,b,c|
   # your code here
end

bar.get(&foo)
jim.get(&foo)
jam.get(&foo)

Placing an ampersand in front of an item in a method call, e.g. a.map!(&:to_i) calls the to_proc method on that object and passes the resulting proc as a block. Some alternative forms of defining your re-usable block:

foo = Proc.new{ |a,b,c| ... }
foo = proc{ |a,b,c| ... }
foo = ->(a,b,c){ ... }

If you are calling a method with a block and you want to save that block for re-use later, you can do so by using an ampersand in the method definition to capture the block as a proc parameter:

class DoMany
  def initialize(*items,&block)
    @a = items
    @b = block # don't use an ampersand here
  end
  def do_first
    # Invoke the saved proc directly
    @b.call( @a.first )
  end
  def do_each
    # Pass the saved proc as a block
    @a.each(&@b)
  end
end

d = DoMany.new("Bob","Doug"){ |item| puts "Hello, #{item}!" }

d.do_first
#=> Hello, Bob!

d.do_each
#=> Hello, Bob!
#=> Hello, Doug!
like image 126
Phrogz Avatar answered Nov 16 '22 01:11

Phrogz