Qwertie
Qwertie

Reputation: 6493

Passing block as variable failing "ArgumentError: Missing block"

I have the method

  def self.fetch(key, &block)
    begin
      Rails.cache.fetch(key, block)
    rescue Redis::CommandError => e
      raise unless e.message == "OOM command not allowed when used memory > 'maxmemory'."

      Utils.log_exception ex
      yield
    end
  end

This fails on line 3 with the error

ArgumentError: Missing block: Calling Cache#fetch with force: true requires a block.

I'm not sure if passing block in as a parameter like that is the correct way but I couldn't see another way.

What is the correct way to pass a variable containing a block to a method?

Upvotes: 0

Views: 130

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

The & ampersand unary prefix operator in an argument list is used to "unroll" an instance of Proc as if it were passed as a block to a method, just like the & ampersand sigil in a parameter list is used to "roll up" a block passed as an argument into an instance of Proc:

Rails.cache.fetch(key, &block)
#                      ↑

Upvotes: 3

Related Questions