1

In a gem I'm working with I found the snippet:

@object.with(&block)

But the method with(&block) is not defined in the project. It looks like it's defined as a base method inside Ruby somwhere, but I'm not sure.

What does it mean? Can someone point to where that method is defined (like in Object or Class or some other Ruby class)?

Edit:

The code in question:

  def self.redis(&block)
    raise ArgumentError, "requires a block" if !block
    @redis ||= Sidekiq::RedisConnection.create(@hash || {})
    @redis.with(&block)
  end

It's from the project Sidekiq (https://github.com/mperham/sidekiq). That project also includes the redis-rb gem (https://github.com/redis/redis-rb). I can't locate a with method defined in either.

Maybe I'm just missing something.

Kevin Bedell
  • 13,254
  • 10
  • 78
  • 114
  • 2
    possible duplicate of [What's this &block in Ruby? And how does it get passed in a method here?](http://stackoverflow.com/questions/814739/whats-this-block-in-ruby-and-how-does-it-get-passed-in-a-method-here) – fotanus Nov 21 '13 at 16:19
  • I understand what the `&block` is -- it's the `.with` method I'm asking about. – Kevin Bedell Nov 21 '13 at 16:22
  • I looked at the linked question and it does not at all address the definition of the `.with` method. – Kevin Bedell Nov 21 '13 at 16:24

1 Answers1

7

It's defined as part of the connection_pool gem which is used by sidekiq, and it's source is below. It looks like it's purpose is to obtain a connection from the pool, yield it to the provided block, and then release the connection back to the pool.

here's how I found that out:

 pry> redis = Sidekiq::RedisConnection.create({})
 pry> redis.method(:with).source

  def with
    conn = checkout
    begin
      yield conn
    ensure
      checkin
    end
  end

pry> redis.method(:with).source_location

["./ruby/gems/2.0.0/gems/connection_pool-1.1.0/lib/connection_pool.rb", 46]

And to identify the dependency:

~$ bundle exec gem dependency connection_pool --reverse-dependencies

Gem connection_pool-1.1.0
  minitest (>= 5.0.0, development)
  Used by
    sidekiq-2.16.0 (connection_pool (>= 1.0.0))
John Ledbetter
  • 13,557
  • 1
  • 61
  • 80