英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论