Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this Ruby function doing?

I am confused on how this returns:

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

It first sets the ENV variable, then sets 'res' to the local value, then re-assignes ENV variable, then returns res?

Not sure I understand how this is convering from UTC to the user time zone?

like image 869
Blankman Avatar asked Dec 10 '10 04:12

Blankman


People also ask

What is the function of Ruby?

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

What does '?' Mean in Ruby?

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false. When you write a function that can only return true or false, you should end the function name with a question mark.

What is &Block in Ruby?

The &block is a way of sending a piece of Ruby code in to a method and then evaluating that code in the scope of that method.

What are procs in Ruby?

A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.


1 Answers

The first line is setting the environmental time zone variable to the user's time zone in order to get the res value in the correct time for that user. If it didn't set it to the user's, the time would still be in UTC.

It then sets the environmental variable back to UTC time, which I assume is the application's default.

It then returns res.

like image 174
Chuck Callebs Avatar answered Oct 23 '22 14:10

Chuck Callebs