Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Time.current over Time.zone.now in Rails, when Time.zone is always set?

The documentation for Time.current says:

Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now.

# File activesupport/lib/active_support/core_ext/time/calculations.rb, line 36
def current
  ::Time.zone ? ::Time.zone.now : ::Time.now
end

But when is Time.zone ever not set in Rails?

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Berlin'

I have commented out config.time_zoneand I still get Time.zone equal to 'UTC' as it apparently sets that by default as the comment mentions. So then, what is the point of using Time.current over Time.zone.now?

PS: I'm observing this on Rails 4.1.16

like image 935
Magne Avatar asked Aug 17 '17 19:08

Magne


People also ask

How do I get current timezone in Ruby?

Ruby Example: Write a program to get the current time zone. Problem Solution: In this program, we will get the current time zone using the zone() method of Time class and print the result.

How do I find time zones in rails?

Time zones in Rails In Rails, to see all the available time zones, run: $ rake time:zones:all * UTC -11:00 * American Samoa International Date Line West Midway Island Samoa * UTC -10:00 * Hawaii * UTC -09:00 * Alaska ... The default time zone in Rails is UTC.


1 Answers

The short answer is there is no difference except cleaner/shorter syntax if you are using Rails as is.

Time.zone_default gets initialized in ActiveSupport::Railtie via active_support.initialize_time_zone. More info on railtie initialization process here.

My guess for reason of this check is that as a framework it is accounting for situation where someone removed this active_support.initialize_time_zone from their rails boot process. In that case Time.zone would be nil.

like image 66
Vijay Agrawal Avatar answered Oct 21 '22 23:10

Vijay Agrawal