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?

1 Answers

3
Jörg W Mittag On Best Solutions

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)
#                      ↑