2012 in Review

This year there has been many changes in my life, so I thought that as a way of reviving this blog, I would share my personal review of my 2012. Hopefully this will entice me to have an even better 2013.

  • I started a new job in february for a consulting firm, a project that has been developed using Ruby and Ruby on Rails, and I have to say that this job has allowed me to train my programming skills like no side project could have done it. I feel that I have a very good grasp of the language and thankfully I’ve had to opportunity to work with a great team, which has led me to improve even more. This job is my first full time job (for the past four years I’ve worked part-time), so the first couple of months were hard in the way that I always finished the work day exhausted and I wasn’t able to do anything after returning home. Thankfully now that I have been working for almost a year, my stamina has gone up, so I am able to come back home and hack on some side projects.

  • I was able to do my first full-TDD side project with Rails, and I have to say that after a couple of weeks I got faster and faster writing tests first, and in my opinion this has led me to have a codebase where bugs show up faster in the terminal that in the browser.

  • Calisto received a major upgrade and changes, and is going to be rebranded soon =).

  • I had the chance to buy and read a whole list of technical books, which have opened my eyes in many ways that would have been impossible unless I read them. Particularly, the book ‘Metaprogramming Ruby’ by Paolo Perrota has had the greatest influence in my code recently, and has even changed the way I approach the design. Other great hits include:

    • Exceptional Ruby
    • Crafting Rails Applications
    • The Rails View
    • The RSpec Book
    • Javascript The Good Parts
    • Javascript The Definitive Guide
    • Don’t Make Me Think
    • Designed for Use
  • I got to try the Try iOS course by CodeSchool and finally understood how is that iOS applications are developed and how they are structured. I didn’t like Objective-C’s syntax so much, but I guess that it’s hard to feel empathy for verbose languages if you’ve been spoiled so much with languages like Ruby on Python.

  • Starting 2012 I got very inspired by reading an article in Mens Journal called Everything You Know About Fitness is a lie and in January I started going to the gym regularly to do barbell training almost exclusively. In two months I was able to raise a lot more weight in bench pressing and squats that I have ever before had, but I stopped going in March because my job’s schedule and my stamina after work was not the same. I plan resuming attending again in 2013, probably before work early in the morning, and tracking my personal metrics to follow my progress.

  • I was able to complete my first glider cross-country flight, 100 kms to be specific, and I loved the experience. 30km final glide of the cross country flight

Overall, I think that I had a good year, and can’t wait for 2013. As a goal I want to learn more about good visual design, and get fit, besides getting even better as a programmer. The pilot inside me will also get more attention and hopefully I’ll be able to call 2013 a success as well.

Bringing Back Ruby 1.9.2 Goodness to Mountain Lion

If you’re still working with Ruby 1.9.2, the upgrade to Mountain Lion is nearly flawless, except that you won’t be able to compile gems dependencies anymore.

Read Thoughbot’s post on upgrading to Mountain Lion for a complete guide to upgrading that Ruby development environment.

Make sure you follow the directions about installing the apple-gcc42 compiler to be able to compile dependencies again.

Using Pry With Pow.cx

As my current warchest of Ruby on Rails projects grows larger, I’ve found that there are better alternatives for development servers than the plain old WEBRick. A good alternative is Pow.

What I like about Pow is that it allows you to have a clean browsing history, because each application you run under Pow lives under its own local dev domain (For example: http://blog.dev, http://clients.dev).

Routes inside each application are be different, and if all of them are always executed under ‘http://localhost:3000’, your routes history is probably messy. Pow helps you with this by isolating the URL per application.

The biggest downside I had with Pow is that I was not able to use pry for debugging. I find pry to be a very useful gem, because it allows me to step into any running request, method, etc (from any controller, model, or test suite), and prompts me with a very rich interactive console.

There’s a gem called pry-remote that enables debugging with pry. It’s very simple to use. Instead of calling binding.pry, you use binding.remote_pry. And then, you connect via the terminal with the command pry-remote.

It’s that simple.

The Importance of Being Eagerly Loaded

I’m working in refactoring a Rails application for a client. Besides doing a lot of refactoring in the views, I started to look at the logs and discovered that the database is being bombarded repeatedly with very similar queries every time you request a page.

I wanted to find out why this happened, and after reading about tuning the performance tuning of Rails applications, I found some material about N+1 queries. Aha. Apparently those fancy methods of accessing associations can bite you in the ass if you don’t use them correctly.

N+1 queries mean that if you ask for all the records of a specific model, and their associated models, Rails is going to query the database as many times as the associated models exists per each parent. So if you roughly had 10 records and 5 associations for each of them, Rails would query the database about 50 times.

In this application we have a big joint structure, and relationships upon the objects are called in almost every view.

Fortunately, Rails being Rails, has a fancy way to reducing the amout of queries done to the database by usign the SQL ‘IN’ clause, that is called ‘includes’.

Checkout the before & after adding ‘include’ in this query:

    #Associations without eager loading
    Page.all.each do |page|
      #...
      page.object_maps.each do |object_map|
        #...
          object_map.object_properties.each do |object_property|
            #...
          end
      end
    end

After implementing include:

    #Associations with eager loading cause the second log
    Page.includes(object_maps: :object_properties).all.each do |page|
      #...
      page.object_maps.each do |object_map|
        #...
          object_map.object_properties.each do |object_property|
            #...
          end
      end
    end

The results are 37 queries to the database vs 3 queries. The difference increases even more when your amount of records grow. Be sure to consider using eager loading if you are suffering performance issues.

Colectivero, Gema Liberada

Hoy publico y libero mi primera gema: Colectivero.

Colectivero es una API no oficial para el sistema de transporte de Rosario, el ETR.

Permite consultar las distintas líneas de colectivo, sus intersecciones entre calles, sus paradas, y su horario de llegada a cierta parada.

La gema está disponible en RubyGems, por lo tanto, se puede instalar con un simple comando: “`bash

gem install colectivero

“`

Para más información y ejemplo de uso, leer el README en el repo de la gema

Dynamic CSS Image Background in Rails

I’m working on some changes to a Rails application for a client.

Today I needed to change the style of a div from a static image background to a more dynamic image. Specifically, I needed the background (because I needed the text in the div above the image) of the div to be an image that was uploaded to the Rails application via the Paperclip gem, so luckily it was accesible via the .url instance method of Paperclip.

After cracking my head against the wall for a while, I remembered a kind of CSS reference that is hated by almost everyone for obvious reasons (lack of encapsulation, repetition of code), but, it was perfect to dynamically alter a value from Rails, so I came up with this solution:

Previously, with a static background: “`css

#application.css
.styled_div {
    background: url("public/background1.jpg")
    ###... Omitted code
}


#app/views/resource/show.html.haml
###... Omitted code
.styled_div
    content that I
    need above the
    background

And now, with the dynamic background: css

#application.css
.styled_div {
    #   background: url("public/background1.jpg")
    # ... Omitted code
}

#app/views/resource/show.html.haml
###... Omitted code
%div{:class => 'styled_div', :style => %(background:url("#{resource.background.url(:medium)}") no-repeat center)}
    content that I
    need above the
    background

“` And it works perfectly. Sometimes it’s useful to be able to be aware of the considered “bad practices” because they can help you get a solution that you wouldn’t have thought about if you only know the “good practices”.

Thread Safe Global Variables in Ruby

Let’s say you have a standard Ruby application, where you decided to use some global variables to ease the access to some standard information that you need across all your code, without resorting to send the global object as a parameter everywhere. “`ruby

    $global_var = SomeClass.new

“`

Now let’s pretend that out of nowhere you decided that you need multiple threads to run your application. Usually you would code something like this to start each thread: “`ruby

2.times do
    Thread.new {
        $global_var = SomeClass.new
        #execute some more code...
    }
end

“`

As your application worked before, you would expect each thread to have its own $global_var but no, global variables are shared among all threads, so suddenly your reports show mixed steps, wrong values in calculations, and everything stops behaving like you would expect it.

This behavior is by design. Global variables are suppossed to be accesible from every single place of your code, so naturally, even though threads are independent, the global variables are not.

So, what can be done to have something between a global variable (to avoid passing it around by value across all your methods), and a local variable (so each thread can have its own and not peek or write outside itself)?

Well, turns out that the Thread ruby class has an instance method to set and get thread-local variables as if the Thread instance was a Hash, and it works just as expected.

First of all you need to reference the running thread. This can be done with the ‘current’ class method: “`ruby

5.times do
    Thread.new {
        Thread.current
        #$global_var = SomeClass.new -- we will not need this anymore
        #execute some more code...
    }
end

“`

And then, you treat the current thread as a hash of key-value pairs: “`ruby

5.times do
    Thread.new {
        Thread.current['local_var'] = SomeClass.new
        #$global_var = SomeClass.new -- we will not need this anymore
        #execute some more code...
    }
end

“`

And that’s it, you can access the value from anywhere within the thread by “`ruby

Thread.current['local_var']

“`

Installing NTFS Support in OS X Lion

For the past 24 hours I’ve been trying to find the perfect way to configure an external hard drive to be able to use it in OS X, Linux and Windows. At last, I decided to go with the dual partition model (one in HFS+ for Time Machine, and the other one in NTFS for maximum compatibility with Windows, and allowing me to save files bigger than 4GB in size)

When I plugged in the HDD in the Mac, I realised that OS X does not have native write support for NTFS.

I did some research and found different solutions: One of them involves buying commercial software like Paragon’s NTFS for Mac and another one involves using open source software.

I decided to go with the second option, and I’ve found that this is the easiest way to install everything in OS X Lion.

Installation steps

1) Download NTFS-3g from SourceForge (The latest version is from 2010 but it works)

2) Install NTFS-3g as usual, but personalize the installation and untick the MacFuse option.

3) Download Fuse for OSX (This is the successor of MacFUSE, which stopped working in the latest versions of OS X)

4) Install Fuse for OSX and make sure that you tick the ‘install MacFuse compatibility’ option.

5) Reboot the Mac (I’m not sure if this is required, but the installer recommends it).

6) Plug in the NTFS drive and you should be good to go