在Ruby中,匿名块传递(&block)是如何工作的?

huangapple go评论64阅读模式
英文:

How does anonymous block forwarding (&block) work in Ruby?

问题

&block 在这个上下文中代表什么?

我的理解是,它代表我们要将时区设置为用户时区之前,将其设置回应用程序默认时区的时间段。

在这种情况下,是指 yield 的持续时间吗?

英文:

I'm using around_action to set the timezone of the Rails application temporarily to the timezone selected by the current user. My code looks like this:

around_action :set_time_zone, if: :current_user

private

def set_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

My question is, what does &block represent in this context?

My understanding is that it represents the duration of time we want to set the timezone to the user's timezone before we set it back to the default for the application.

In this case is that the duration of the yield?

答案1

得分: 2

根据 https://api.rubyonrails.org/classes/Time.html#method-c-use_zone

use_zone(time_zone)
允许在提供的块内本地覆盖 Time.zone;完成后将 Time.zone 重置为现有值。

所以时区的更改只在传递给此方法的块内部可见。

看一下:

    Time.zone = "London"

    Time.use_zone("Eastern Time (US & Canada)") do
      puts Time.zone
    end

    puts Time.zone

输出是:

(GMT-05:00) Eastern Time (US & Canada) # 块内部
(GMT+00:00) London # 块外部
英文:

According to https://api.rubyonrails.org/classes/Time.html#method-c-use_zone :

>use_zone(time_zone)
>
>Allows override of Time.zone locally inside supplied block; resets Time.zone to existing value when done.
>
> # File activesupport/lib/active_support/core_ext/time/zones.rb, line 61
> def use_zone(time_zone)
> new_zone = find_zone!(time_zone)
> begin
> old_zone, ::Time.zone = ::Time.zone, new_zone
> yield
> ensure
> ::Time.zone = old_zone
> end
> end

So the change of the time zone is visible only inside the block you pass to this method.

Take a look:

    Time.zone = "London"

    Time.use_zone("Eastern Time (US & Canada)") do
      puts Time.zone
    end

    puts Time.zone

And the output is:

(GMT-05:00) Eastern Time (US & Canada) # inside the block
(GMT+00:00) London # outside

huangapple
  • 本文由 发表于 2023年7月4日 23:05:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定