Lazy enumerator to handle huge files


Bookmark and Share

Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed. It’s frequently seen in functional languages, ruby introduced the lazy method in Ruby 2.0. For those who don’t know what are enumerators: enumerators are something that can be counted. So a collection of elements, files (file is an collection of lines of string), etc can be treated as an enumerator.

In ruby we need to make something countable into an enumerator object, which is done by applying .each and .map on it.

Ruby has a wide range of operations we can do over a collection, it’s one of those features that makes Ruby such a powerful dynamic language. An enumerator can be used to generate series like the Fibonacci series.

But when we do a .map / .each with a code block, then it would try to realize the enumerator fully and then apply the block over it.

That would be fine when we are working on something small like:

But when we take the above fib enumerator, which will grow into an infinite series, adding a .map would lead the code to an infinite loop. If you are crazy enough to write an infinite loop, …

Read More

Working with timezones in rails


Bookmark and Share

Ruby on Rails being an amazing framework, helps us manage the timezone of our rails application. It gives us access to a lot of helpers, to make our life easier. For example, if you want to change all the date and time of your application to the logged in users time zone, we just have to place the following code in the application_controller.

We assume that you have stored the user’s time_zone in your database in the time_zone column.

The application  to show  timezone can be set in your application.rb, if we don’t set a particular timezone then the application will just show the systems timezone.

If you want to know all the timezone options available in rails, run the rake -D time command in your terminal.

Even though rails would take care of the timezone, when we are using certain ruby commands, it gives us our systems timezone and not the one set by rails. So to avoid surprises, we should be aware of the timezones we are exposed to.

A rails app, would always be exposed to three timezones:

  • System timezone
  • Database timezone
  • Rails applications own timezone

All three could be different, for example your system timezone could be in …

Read More