简体   繁体   English

Ruby中的“ with(&block)”是什么意思?

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

In a gem I'm working with I found the snippet: 在与我合作的gem中,我找到了代码段:

@object.with(&block)

But the method with(&block) is not defined in the project. 但是with(&block)方法未在项目中定义。 It looks like it's defined as a base method inside Ruby somwhere, but I'm not sure. 看起来它已被定义为Ruby somwhere中的基本方法,但我不确定。

What does it mean? 这是什么意思? Can someone point to where that method is defined (like in Object or Class or some other Ruby class)? 有人可以指出该方法的定义位置(例如在Object或Class或其他Ruby类中)吗?

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 ). 来自项目Sidekiq( https://github.com/mperham/sidekiq )。 That project also includes the redis-rb gem ( https://github.com/redis/redis-rb ). 该项目还包括redis-rb gem( https://github.com/redis/redis-rb )。 I can't locate a with method defined in either. 我找不到在with定义的with方法。

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. 它被定义为sidekiq使用的connection_pool gem的一部分,其来源如下。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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