简体   繁体   中英

What does “with(&block)” mean in Ruby?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM