Thursday, December 31, 2015

Programmers and Obsessive-Compulsive Disorder: a hint for beginners



I think we, programmers, all have felt, one way or another, that compulsion to put things in a certain order.

Identation is an example. In the last 30 years programming, I've met just a few programmers who couldn't care less about identation. None of them is still a programmer by now. It seems this feeling about organizing program's lines is essential when it comes to be a good programmer or not.

It is kind of a positive Obsessive-Compulsive Disorder. And I say positive because keeping things organized helps a lot in programming.

Have you ever felt unconfortable when you add a column to a table using a migration and then you have things like

  create_table "courses", force: :cascade do |t|
    t.integer  "user_id",           limit: 4
    t.string   "title",             limit: 100,   null: false
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.binary   "short_description", limit: 1024
    t.binary   "long_description",  limit: 65535 
  end

Here you clearly see that columns short_description and long_description are out of order. And, worst of all, they are going to be out of order in your table. I mean out of order because I assume all columns should come before created_at and updated_at. This is so natural to me that I can't even explain why is that so. But it is! Maybe it is really Obsessive-Compulsive Disorder.

The good news for beginners is: you can safely edit your db/schema.rb to fix this!

In spite of what Rails writes in this file by default, you can safely edit db/schema.rb, as long as you do nothing more than changing the order of some lines inside a create_table.

In the case above one may edit db/schema.rb and write


  create_table "courses", force: :cascade do |t|
    t.integer  "user_id",           limit: 4
    t.string   "title",             limit: 100,   null: false
    t.binary   "short_description", limit: 1024
    t.binary   "long_description",  limit: 65535 
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
  end

Then, the point here is:

  1. Generate all your migrations
  2. Run rake db:create:all
  3. Run rake db:migrate
  4. Edit db/schema.rb and place all columns in the correct order
  5. Run rake db:drop:all && rake db:create:all && rake db:schema:load
And voilĂ ! There you have all your columns, in all your tables, in the correct order, no matter how you created them.