What I love about Ruby

I talk about Ruby all the time, even being proficient with other languages (such as C, Java and C# – but not C++). Why is that? Well, Ruby has a lot of incredible features that you may find on other languages, but generally are not on static languages:

1 – Code blocks and lambdas

I talked a little about them in a previous post. While a lot (really, a lot) of languages have support for anonymous functions and closures, the “big ones” don’t*. And the way that Ruby implements that is so elegant that most newbies don’t even know they are using a closure, or what would be that.

Actually, C++ (since C++11) and C# (we could use delegates since C# 1.0, but it evolved until C# 3.0) have anonymous functions, and C can do something similar using pointer to functions. Java, on the other hand, doesn’t have anything similar (but everybody is hoping it to implement that on Java 8). But the way Ruby handles that is just so elegant. For example, I can easily select all the non-null entries of a given Array @array with:

non_nil = @array.select { |x| x != nil }

2 – Metaprogramming

Check this:

class Numeric
  def method_missing(m)
    time_hash = { "seconds" => 1, "minutes" => 60, "hours" => 3600 }
    if(time_hash.has_key? m.to_s)
      return self * time_hash[m.to_s]

Now I can use the methods “seconds”, “minutes” and “hours” in any numeric object, and with a really DRY code!

These methods are created at run-time, whenever they are needed. Ruby can do that. And it can do more (Rails uses a lot of metaprogramming on ActiveRecord). It’s a really big subject, and I could spend a lot of time talking about that.

3 – Open classes

Have you seen what I’ve done in the previous code? I changed the behavior of the Numeric class. I can do that with any class, have I created it or not. Even built-in classes can have its behavior subscribed.

Now, a lot of people won’t like that, and they have some reasons. And while they can be right sometimes, it is much better to simply change the behavior of a built-in class than to always use a child class on the whole application.

4 – The object model

Everything in Ruby is an object. And when I say everything, that’s everything. Even classes are objects (of the class Class). That means you can create and manipulate almost everything inside of Ruby in runtime.

There are other reasons for why I love Ruby, but these are the main ones.


Ajax on Rails step by step

My previous post about Ajax was aimed to people who knows how to actually make an Ajax solicitation, but this is not the case for people who are beginning. So, I’ll explain better how to do this. I’ll teach it using CoffeeScript and JSON, but you are free to trade technology as much as you want (using Javascript and XML, for example).

What is an Ajax solicitation?

I’m going to be really objective here: an Ajax solicitation happens when you want to request some data from the server (or send it) without reloading the page, and process it with a Javascript callback.

For doing this, you must do three things:

  1. Your server must provide the data via HTTP;
  2. You must make a solicitation;
  3. You must have a callback function for when the solicitation arrives

Provide data via HTTP

That’s really simple. The server does not care if the solicitation is Ajax or not, so every data the server provides you can be retrieved in Ajax. For example, let’s say you have this controller:

class FriendsController < ApplicationController
  def show
    @friend = Friend.find(params[:id])

    respond_to do |format|
      format.json { render json: @friend }

You can retrieve a JSON representation of the friend with id 1 with “GET /friends/1.json”. It doesn’t matter if you requested it from a regular link or an Ajax link, the server will send you the same JSON.

So, it’s really easy on the server side: you can simply remain with your current controllers. At most, add JSON representations to your resources.

Make a solicitation

Generally, an Ajax solicitation is more confuse and obscure. Not on Rails. If you want a link to make an Ajax solicitation, you just have to add the “remote” attribute to it.

For example, if you want to make a link to make an Ajax request from “/friends/1.json”, simply do this:

<%= link_to "Awesome ajax link!", "/friends/1.json", remote: true, id: "ajax_link" %>

And that’s it! You have a Ajax link! It doesn’t do anything yet, but it will on the next step.

I added the “id” to the link so I can pick it easier with jQuery. But you don’t need to, if you want to make it another way.

Make a callback function

Ok, now the “difficult” part. When the response from the solicitation comes, you have to do something with it. But how do you know when the moment came?

You don’t. But the browser does. So tell the browser to call a function when the solicitation comes:

$(document).ready ->
    successCallback = (e, xhr, settings) ->
        myData = jQuery.parseJSON(xhr.responseText)
        # Do whatever you want here. Scramble your DOM, make an alert.
        # Everything you need is in the myData variable
    $('#ajax_link').bind("ajax:success", successCallback)

Ok. That’s not so difficult.

And this is not everything! You can make POST, PUT and DELETE via Ajax, too! Actually, you can do everything! And you do not need to change a lot of things on this tutorial, only how you’ll handle the data you are sending.

Working with lambda functions in Ruby

Ruby provides an easy way of working with closures: the code blocks. Everybody that uses Ruby for a minimum amount of time knows how code blocks work. You can do it this way:

def foo(a)
  # Some code here, create n
  # More code here

# Some code here, create x
foo(x) do |y|
  # Your code block goes here. You can access any variable from previous scope
  # But everything created here is exclusive for this scope

Or like this:

foo(x) { |y| do_stuff_here }

This is a lot similar, but not exactly equal, to what you can do with a functional language (where you can, for example, pass a function as an argument to another). Code blocks are really practical, but they have some limitations:

  1. You can only pass one block per function;
  2. Blocks can’t return anything. If you need the result of an anonymous function, blocks are not what you need. That’s because the return is non-local; that is, the function that is declaring the block will be the one returning.
  3. You can’t pass the same block more than once, because you can’t storing it anywhere.

But there are two other ways of creating anonymous functions in Ruby that addresses some or all of these problems: procs and lambdas.

1. Procs

Actually, I lied. You can store blocks somewhere. And the place is a proc.

Blocks are, actually, a way for creating procs. They are the same type of closure: they have access to the scope that creates them, their return is non-local and they can be passed as a parameter to another function. If you try to call a proc with additional parameters, they will be ignored, just like it would happen on blocks.

Generally, it is better to use a block than a proc, except when you need to pass more than one to a function or when you want to send the same block to two functions.

But how do you use a Proc?

Simple enough:

def receiver_method(parameter)
  y = 5

test_proc = Proc.new { |x| x * 3 }
puts receiver_method(test_proc)

This will print 15 on the screen.

2. Lambdas

Lambdas are similar to procs, but there are two main differences:

  1.  If you try to pass the wrong number of parameters to a lambda function, it’ll throw an error
  2. Lambdas can return values without affecting the callee

That is, you can create a lambda function like this:

fat = lambda do |x|
  result = 1
  1.upto x do |i|
    result *= i
  return result

And call it wherever you want that it’ll not affect the flow of the code. In this aspect, lambda functions are similar to regular functions.

Beginning in Ruby 1.9, there is a cleaner syntax for creating lambda functions:

square = ->(x) { x * x }

And actually, lambdas are ALSO procs internally. But this doesn’t matter a lot from a pragmatic point of view.

So, that’s it. Whoever likes functional languages, Ruby has the tools for the job.

Git commands you should know

Git is one of the most powerful VCS’s on the market. Yes, there are other great VCS (as Mercurial and Bazaar), and it has its problems (the cryptic documentation, the transcendental meaning of git-reset, etc.). But the collection of tools it provides to you is capable of diminish any difficulty.

There are some tools that don’t seem useful at first, but will come incredibly handy sometimes. For instance,

#1 – cherry-pick

Picture this: you’re working on a feature branch. You see some minor bug from your main development branch while you’re working on it, so you commit a correction for it. The feature doesn’t come out as expected, so you delete the branch and remake the change on the main development branch. Right?

Well, you could do that. But you could also use the git cherry-pick.

This command takes a commit identifier as a parameter, and applies the commit to your current branch. Simple and clean.

After you applied the commit, you can fearlessly delete your failed feature branch.

#2 – bisect

Bisect is an awesome tool, and is implemented across various DVCS’s. The concept is really simple: at some point, someone made a bad commit that inserted a bug in your code. You don’t know where the bug is, or how it began.

Now, you may debug your whole software until you find the line that inserts the bug. But this is laborious, and doesn’t guarantee you have a solution (for example, the bug is inside a CSS. How to debug it?)

So you use bisect. You know that the current branch (let’s say, feature-x) is broken, but the tag v1.0-12 didn’t have the problem yet.

So, you do this:

git bisect start feature-x v1.0-12

And test your software. This will select the middle commit between your feature-x branch and your v1.0-12 tag. If the bug disappeared, you mark the current commit as “good”. If it’s there, you mark it as “bad”. If you can’t test the current commit for some reason, you skip it. If you want to see a log with the commits that git is suspecting to have the bug, it’s also possible.

git bisect good
git bisect bad
git bisect skip
git bisect view

When it finishes, it will tell you in what commit the bug was inserted. So you reset the repository to your current HEAD. Always remember to do that.

git bisect reset

Then, you can edit your files accordingly.

#3 – gitk –all $(git reflog –pretty=format:%h)

Pretty monster, uh? Test it now. It’ll show every commit you made, even those that are not reachable anymore. Sometimes it may be useful. In pragmatic terms, it’s a reflog inside of gitk.

#4 – rebase –interactive

It opens your text editor with a script that allows you to squash, edit, reorder or delete commits from your current branch, based on the parameter you gave. For example, if you are on master and insert a

git rebase -i origin/master

You’ll edit the commits that are not present yet on origin/master.

NEVER use this command with commits that already public, otherwise you’ll make your friends really upset. 😦

#5 – add -p

This command allows you to interactively select which parts of the file you want to stage, allowing you to commit only a specific part of the file. Use “?” for help. It’s pretty intuitive.

If you know more useful commands, let me know on the comments.

Don’t send Javascript as an Ajax response

In this post, I’ll assume that Rails’s asset pipeline was a good choice. This debate is irrelevant to this post. If you don’t like CoffeeScript, use Javascript.

I’ve read a lot of Ruby on Rails books, including Head First Rails, Ruby on Rails Up and Running, The Rails View, and also some Brazilian authors.

All of them made the same mistake, which brought me a lot of trouble: they teached that, in order to handle an ajax response, you have to make the requested controller send back a Javascript. Some of them even told that you should use “render :update” for it! I don’t know about other authors, maybe I’m simply unlucky.

Back at those times, my controllers were awful, filled with obscure code. So a lot of more experienced programmers told me that I could create a view, like “index.js.erb”, to generate the Javascript.

Something was still wrong. I thought to myself “but wouldn’t be a lot better if I requested some data and a callback function handled this data for me? Every Ajax book I’ve seen teaches me to do this! Why should it be so difficult with Rails?”

In fact, it’s not. It’s really easy. And it makes more sense.

Why would they pack Rails with CoffeeScript, if the controller would process a “js.erb”? You can and should handle the response with a CoffeeScript callback.

How to do that? Simple enough:

$(document).ready ->
    $("a#link_id").bind "ajax:complete", (e, xhr, settings) ->
        # TODO: the callback function goes here

This will go on app/assets/javascripts/<current page’s controller’s name>.js.coffee

You can put whatever you want to identify your link (or form) instead of “a#link_id”. Of course you can define the callback function outside of the bind and pass it as a parameter.

The content of the response is inside of xhr.responseText. For example, if you requested a JSON, you can do that:

response = jQuery.parseJSON(xhr.responseText)

And you’ll have all the data from the server.

There are also other Ajax events that may help your page to have a more responsive interface:





ajax:complete (it is after a success OR a failure, so don’t use it instead of ajax:success)

ajax:after (after the request is sent, not after the response was processed)

But why bother with this? Won’t a Javascript response work?

Well, there are a lot of situations where a Javascript response wouldn’t work. For instance, in this page (yes, it is an awful page, but it was only a concept test).

I needed each of these submit buttons to show my data in a different way. But the data I needed would be always the same. I could use three links and update them whenever the select changed, but this would not be practical at all. This was a lot simpler:

$("#report").bind "mousedown", ->
    $("form").bind("ajax:complete", reportCallback)

$("#graph").bind "mousedown", ->
    $("form").bind("ajax:complete", graphCallback)

$("#pizza").bind "mousedown", ->
    $("form").bind("ajax:complete", pizzaCallback)

There are situations where two different pages also need the same data, but they will also process them differently. A callback function would also be the best approach for it. As a general rule, getting data and processing it with a callback function will almost always be better.

For more information on the subject, I’d recommend you to read the excelent article from John Gadbois called Using Unobtrusive JavaScript and AJAX with Rails 3

The Dharma of Programming


Programming like a Buddha

Being a developer/programmer is not an easy task. Any of us could say that. But why is it so difficult?

Well, the main reason is simply that: it is difficult. It is challenging. We have to put our brains to deep thinking to solve real world problems. And the problem can vary from calculating some taxes to detect an anomaly on a electromagnetic field. This is what makes our jobs interesting and give us passion: we like to solve problems.

But, there are other reasons for that. The thing that stress us out and demotivates us: work on somebody else’s code. This includes work on legacy codes, making changes on software with awful design (that doesn’t respect any design principles) and correct their bugs.

I hate that. And what I hate the most is the amount of programmers that makes code only to “solve” a specific problem, without even understand what the problem was on the first place. You know at least one of those. But they are not this rare, they are everywhere. And they make unreadable code. They make repetitive code. They make code that is hard to modify and maintain.

Because of those guys, I created the Dharma of Programming, inspired by Buddhist principles. This will not be the theme of this blog (I will talk about programming in general, focused on Ruby and Rails), but it will be the start.

The Dharma of Programming comprises of four simple principles (The Four Simple Principles. Yes, that’s the name. I inspired myself on the Four Noble Truths). They may seem very simple and intuitive, but remember that I’m making these for people that don’t understand such simple things.

  1. Problems exist. Every piece of software is trying to solve a specific set of problem. When you are trying to solve a bug, you are trying to solve a problem. You are always solving problems. That’s what it means to be a programmer. Yes, even game developers.
  2. The problem always have a cause. Always. The cause of tax calculations are… taxes. The cause of a bug is some mistake.
  3. If you understand the cause of the problem, you can solve it. If you understand how an anomaly on the electromagnetic field happens, you can make a software that detects it (if you have the tools, obviously). If you understand WHY the error is happening, you can stop it from happening.
  4. To solve a problem, you may follow a path (The Simple Fourfold Path, inspired on the Noble Eightfold Path).

The Simple Fourfold Path is what follows:

  1. Right View: understand the problem and the cause of it. Please. This is the most important thing. Don’t try to solve a problem without understanding it.  (Actually, do try. There are a lot of contexts when digging the problem is the best way to understand it. But don’t consider the problem solved while it’s not understood. If it works and you don’t understand how, in some moment it won’t work). Don’t be afraid of asking for help. Read the error message (seriously, READ IT. Most of the times, when I have a problem, I solve it simply by reading what the error is. And it irritates me when somebody else could solve a problem by reading it and googling it).
  2. Right Concentration: concentrate yourself on solving the problem. Think about it. Seriously. Think. Don’t try to solve it before thinking, you won’t understand if you don’t.
  3. Right Action: learn design principles. It may seem useless when you work alone, but it’s not. When you are the “dumb programmer” I’m talking about, you get irritated with yourself. Make code that is easy to maintain. Don’t Repeat Yourself. Keep It Simple. Make it SOLID. It will help you later. Seriously. Software always change (if it’s good enough, at least).
  4. Right Effort: don’t try to solve “the easy way”. There is no easy way. There are simple ways, but this is not the same thing. If you try to solve a problem the “easy way”, see it as a trigger. It will explode, sooner or later. So, do your job and solve it. If it’s too difficult, try to get more people to help you out.

Well, that’s it. Everything is really obvious. So, if it’s obvious, please, do it.