What does this Ruby function do?

I am confused about how this comes back:

def utc2user(t) ENV["TZ"] = current_user.time_zone_name res = t.getlocal ENV["TZ"] = "UTC" res end 

First, it sets the ENV variable, then sets the "res" to a local value, then overrides the ENV variable, and then returns res?

Not sure if I understand how this happens with UTC in the user time zone?

+6
ruby ruby-on-rails
source share
4 answers

The first line sets the value of the environment time zone variable in the user time zone to get the res value at the right time for that user. If he did not set it to the user, the time will still be in UTC.

It then returns the environment variable to UTC, which I assume is the default application.

Then it returns res .

+7
source share

The getlocal method uses ENV ["TZ"], so it's just a little dance to temporarily set it up, use it, and then bring it back.

Although in this case he was β€œreturned” to β€œUTC”, and not what was before, which seems a little dubious. And there is an in_time_zone method for this directly, anyway!

+4
source share

It returns the time according to the time zone name specified by current_user.time_zone_name , calling getlocal on the object passed in Time .

Then it resets the current time zone to UTC and returns the Time object returned from getlocal during this call (i.e. when the environment time zone was what the user time zone is).

+2
source share

This function takes time as an input, it passes the time zone to users in TZ, so when the getlocal method is called, it actually gets time based on the user local time zone and not UTC. Then it returns the envt TZ variable back to UTC and actually returns the local time zone of users in the last line.

+2
source share

All Articles