A list of books for the wannabe programmer

Since i’ve been evangelizing many friends about ruby, technology and programming, i’ve decided to come up with a list of books i would recommend to those that want to be a programmer (and a few tips mixed in).
Here it goes:

  1. Learn to Program – Chris Pine – Pragmatic Programmers – this will introduce you to ruby and programming in general. quick’n'easy. don’t skip the exercises!
  2. Install ubuntu – you don’t want to get to program on windows machines
  3. Before going further, learn how to use the vim text editor – plenty of articles and tutorials are available on the web
  4. Read Programming Ruby 1.9 – Dave Thomas, Andy Hunt and Chad Fowler – Pragmatic Programmers – A great ruby book, will explain to you all of the details
  5. You probably got a bit confused about object-oriented designs. Read Object-Oriented Thought Process – Matt Weisfeld
  6. Before starting on web development, you gotta learn some easy languages such as HTML and CSS – W3 Schools is a way to go!
  7. Do yourself a favor and learn JavaScript (W3Schools) and then jQuery
  8. Learn a bit about databases – W3 Schools has a quick introductory course that will fit
  9. Read Agile Programming with Rails – Pragmatic Programmers
  10. Get to know testing, read The RSpec Book – David Chelimsky
  11. Learn the black magic with Pragmatic Metaprogramming Ruby – Paolo Perrota

Of course, this should be coupled with a LOT of training and living the software builder experience!

No Comments

Installing a D-Link DWA-125 Wi-Fi on Ubuntu 11.04

We’re modernizing the office on Kimitachi and bought a couple of DWA-125 Wi-Fi dongles in order to get rid of the ugly and bad cables (yeah i know they’re not bad but..)!

Everything was going fine: plug and play, network recognized, connected and ta-da! slow connection! slower than the slowest cripple snail!

Fortunately, since i use ubuntu, a lot of folks have had this problem before me and, from the hundreds of non-working solutions i found, i came out with a little simple guide that works as a charm for me:

  1. Disable IPV6 – Go to /etc/sysctl.conf and add the following line: net.ipv6.conf.all.disable_ipv6=1
  2. Blacklist the mean module that is controlling your dongle (code below)

On /etc/modprobe.d/blacklist.conf

blacklist rt2800lib
blacklist rt2800usb
blacklist rt2x00lib
blacklist rt2x00usb

And that’s it! Go get that 10GB download!


So you got the gem install activerecord-mysql2-adapter problem?

Today while installing a little sinatra app into a friend macbook, i ran into the following piece of hell:

`establish_connection’: Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (no such file to load — active_record/connection_adapters/mysql2_adapter) (RuntimeError)

As i couldn’t possibly find that gem, i started searching the internet after a solution. About an hour later (and several frustrated attempts) i was finally able to solve the problem by issuing the following command:
sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /lib/mysql2/mysql2.bundle
Note that you need to replace with the current path to mysql2 gem (if you use rvm, chances are that it is like
Hope it helps!


Recipe to end multi-monitor hell on Ubuntu

Today i’ve spent a couple of hours trying to fix my multi-monitor configuration on ubuntu. Note that I use a Radeon HD5830 with two monitors, and an extended desktop.
When you use the Monitors Tool, configure the monitors and then restart X, the X server seems to crash. The same happens if you use Catalyst Control Center.
My recipe to fix this behavior is the following:

  1. Connect both monitors
  2. Go to Catalyst Control Center and configure them properly (needs administrative privileges)
  3. Apply your settings
  4. Disconnect Monitor 2
  5. Log out and wait for login screen to appear
  6. Connect Monitor 2
  7. Voilá! You got it!

Couldn’t be easier!

1 Comment

A Beginner Guide to Creating Class Macros

If you are an experienced rubyist or at least have taken time to play with Rails or many other ruby gems, chances are you have already seem code like this:

class Person < ActiveRecord::Base
  has_many :books # <---- that's what i'm talking about!

The first time i’ve stumbled upon one of these weird “things”, i’ve figured that somehow the gem had created a new language construct or something alike that scared the hell out of me!

That’s until i’ve finally came to know that when you are declaring a class, you’re actually executing code, not only declaring methods, constants and instance variables. So, after all, code like the one above is simply calling a method from within a class definition.

At first look, it seems that it would be pretty useless to execute code inside a class definition instead of within a method, but when the ruby flexibility and power come to play, you’re really empowered by this possibility as it allows you to create new methods, modify object behavior, redefine instance variables – and much more – dynamically! Let’s see an example:

# I assume that a 'buzzer' function simply puts "Bzzzzz"
class Foo
  define_buzzer :lucas
Foo.new.buzz_lucas # -> Bzzzzz

The example above will create a method that is named according to a symbol you give as an argument. If that doesn’t look straightforward to you, let’s try another example:

class Foo
  define_buzzer :lucas, :extra_buzz => "Hey! Hey! Hey!"
Foo.new.buzz_lucas # -> Bzzzzz Hey! Hey! Hey!

Now that’s something you might want to use: a dynamically named class that generates dynamically modified code! So instead of writing this:

class Foo
  def send_welcome_mail
    subject = "Welcome E-Mail"
    to = customer.email
    from = "Welcomer <welcomer@foo.bar>"
  def send_purchase_mail
    subject = "Your purchase has been confirmed!"
    to = customer.email
    from = "Foo Sales <sales@foo.bar>"

You could simply write this and get the exact same functionality, without the messy repetition:

class Foo
  def self.define_mailer(*args)
    define_method "send_#{args[0]}_mail" do
      send_email(args[1][:subject], args[1][:to] , args[1][:from])
  define_mailer :welcome, :subject => "Welcome E-mail", :from => "Welcomer <welcome@foo.bar>", :to => customer.email
  define_mailer :purchase, :subject => "Your purchase has been confirmed!", :from => "Foo Sales <sales@foo.com>", :to => customer.email

Actually there’s much more that you can do with this powerful possibilities ruby gives you – which are outside the scope of this little introduction – but let’s start with the basics: how can you start creating your own class macros and get that “how the heck did you do that?” look from your fellow non-rubyist friends (if you are like me, chances are there won’t be much that are outside the ruby club yet :).

Part One: Define class methods to define macros that can be used within a class

When you are inside a class definition, all method calls are directed to the class of the class you are defining (which is Class, and that’s a weird sentence, isn’t it?). When you define methods using the: def self.class_method declaration, you are inserting the method into an intermediary class that is between the class you are defining and it’s class (which is Class, remember?) – some folks call this intermediary classes singleton classes or eigenclasses – so this way whenever you call a method inside a class definition, the interpreter will look for that method firstly in this “intermediary class” and then in the class Class (oh dear..) and up to the parent-of-all-parents Object (or, on ruby 1.9, BasicObject) class.

This means that if you define class methods to a class, you can actually call these methods inside the class definition to get the functionality we’re looking for! Let’s try that:

class Foo
  def self.create_mother_call_for(name)
    define_method("call_#{name}_mother") do
      puts "Hey #{name}'s mother! Come here!"
  create_mother_call_for :john
Foo.new.call_john_mother # -> Hey john's mother! Come here!

And that’s it, you’ve created your first macro!

Part Two: Let’s broaden the horizon defining those methods inside Modules!

Let’s say you got shared functionality between some classes (you have, don’t you?) and it’s pretty repetitive stuff but not enough to violate the Single Responsibility Principle and to create another class to handle that. It seems like a good time to use our recently-learned class macros to help us there. To use class macros that live outside the class methods, you can use a method called extend, which includes module methods into that “intermediary class” we talked about (and that’s the last time  i’m calling them like that! From now on you’ll hear eigenclass!). Nothing better than an example to show how beautifully you can do that:

module MotherCaller
  def create_mother_call_for(name)
    define_method("call_#{name}_mother") do
      puts "Hey #{name}'s mother! Come here!"
class Baby
  extend MotherCaller
Baby.new.call_john_mother # -> Hey john's mother! Come here!

And it works just as you wanted! Class macros can now be included into any class’ eigenclass!

Part Three: You’re getting excited aren’t you?

I really wanted to give just an introduction to those of you that never heard of this kind of ruby trick, so it’s totally out of the scope of this simple blog post to talk about some pretty serious stuff you can do with class macros and metaprogramming. So, to help those of you who want to learn more, here goes a bunch of resources you can use to learn more about this kind of trickery:

I really recommend you dig deep into this topic since it allows you to fully understand some advanced code and create solutions in a very specific, creativity-enabling way!

Do you have any thoughts on this? Comments are more than welcome!


Message Expectations on methods that receive multiple messages with RSpec

Suppose you have the following scenario:

class Foo
  def bar
    [:foo,:bar,:zoo].each { |var| instance_variable_set("@#{var.to_s}", rand(5)) }

And you want to specify that Foo should receive instance_variable_set with :foo, :bar and :zoo. You can try this way:

describe Foo
  describe "#bar"
    subject { Foo.new }
    it "sets the instance variable @zoo with a random number" do

But this way when #bar calls instance_variable_set with :foo or :bar, you get a Spec::Mocks::MockExpectationError: “#<Foo:0x7f770e216d08> received :instance_variable_set with unexpected arguments”. Great, ain’t it? How are we supposed to fix that?

Here’s something that should work in this case:

describe Foo
  describe "#bar"
    subject { Foo.new }
    it "sets the instance variable @zoo with a random number" do

Since you don’t care, in this example, what instance_variable_set does, you can stub it as a null_object, which won’t complain when it gets unexpected messages. So instead of the #bar method actually calling instance_variable_set, it calls the stub!

Do you still want to assert that instance_variable_set is doing its job on setting variables? Then it’s a behavior that should be specified on another example! An example would be the following:

describe Foo
  describe "#bar"
    subject { Foo.new }
    it "sets the instance variable @zoo with a random number" do
      subject.stub(:rand => (fake_random = double('fake-random')))
      subject.instance_variable_get("@zoo").should == fake_random

This approach is fairly simple and works as it should, letting you specify your code behavior without bothering with the need to assert that “ruby is doing its job right”.

What about you? Do you have any magic you would like to share about setting message expectations? Feel invited to comment!


Mocking Kernel Methods with RSpec

Sometimes you might want to set message expectations on the Kernel Module methods like open, puts, etc (more). Trying to mock Kernel.open i found out that the message expectation fails to catch the call to the method when you set the expectation as:


So, after a little searching, i realized that when you call Kernel methods from within a class, you can mock the method you want to call directly in the class, as in:

class MyTestClass
  def say_hi
    puts "Hi!"
# Expectations
describe MyTestClass do
  describe "#say_hi" do
    subject { MyTestClass.new }
    it "should say hi" do

When you call puts from within the class Test, self is set to the object itself, and it acts as the receiver for puts. If you don’t implement puts, the interpreter goes up the class chain looking for the method until it finds it in Object, that mixes in the Kernel module!


Stubbing Class Constants when Testing

Today i ran into a spec that needed to override a class constant in order to assert that its members are called by an iterator and used inside the code. It wasn’t simply an implementation detail as i needed to make sure everything was working as it should in a kind of complex environment.

At first, i thought of performing a class_eval to reset the constant, which did not work. Later on i’ve used const_set and as it worked it would send a warning that looked pretty ridiculous right in the middle of my specs: warning: already initialized constant A

A few hours later, after running into ruby-doc several times, i created a solution that seems to be working like a charm (at least until now!). It was made with the RSpec processing standards in mind but it should work with other testing frameworks as well by using the same logic:

# Stubbing class constants
describe "stub class constants" do
  before(:all) do
    @new_constant = mock('new_constant')
    @old_constant = ClassThatHasTheConstant::Constant  
    # saves the old constant for future resetting
    # tells the class to remove the constant through __send__ because :remove_const is a private method
    ClassThatHasTheConstant.const_set('Constant', @new_constant)  # set a new constant with a new value
  [ ... ] # your examples here
  after(:all) do
    ClassThatHasTheConstant.const_set('Constant', @old_constant)

Is there a better way to do this? Am i violating any principles of good programming? Please comment below! :)


Keep Controllers Organized: The Shared Helper method

Have you ever felt like your controller was getting a lot of private methods to maintain its code clean? Better yet, have you ever felt that those chunks of code could be used elsewhere in your application, helping keep your code DRY?

I was hit by this thoughts a while back when i was starting developing with rails and the method i used back then seems to be pretty straightforward to me, even now (one year later). The principle is simple: Take reusable chunks of your code that can be used on different controllers, glue them up in a helper module and include that module on every controller that uses the code.

I usually split the methods into subjects, like UserSharedHelper for user-related methods, PurchaseSharedHelper for purchase-related methods and so on…

Let’s see an example of this practice in action:

module UserSharedHelper
   # Require an user to be logged in.
   def require_current_user
      # if there is a current_user, then the user is logged in and
      # the action can proceed
      return true if current_user.present?
      # if the method hasn't returned, there is no user logged in!
      # flash a warning and redirect the user to the log in page
      flash[:warning] = "You must log in before proceeding!"
      redirect_to new_user_session_path
class StoreCheckoutsController &lt; ApplicationController
   include UserSharedHelper
   # require users to be logged in on actions under this controller
   before_filter :require_current_user
   def new; end

It’s pretty simple and helps you to keep your code DRY. There are some drawbacks though that need to be considered:

  • The controller scope gets methods from the SharedHelper, which may lead to method conflicts;
  • As your SharedHelpers grow larger, you gotta be careful with injecting a lot of unnecessary code into your controllers;
  • Methods from the SharedHelper make their way into the view, which may lead to further conflicts.

Being used with careful, i don’t see a reason not to use it. What about you? How do you keep your controllers DRY? Comment below!


Guillermo commented with a pretty straightforward way to make this approach even better:

Defining the module:
And in the controller:


OpenTTD OpenMSX musics not playing on Ubuntu?

IOpenTTDt has been a week since i’ve started remembering some good times when i used to play OpenTTD. Today i’ve decided to give it another try for the past sake!

I’ve downloaded OpenTTD along with OpenGFX (Graphics), OpenSFX (Sound FX) and OpenMSX (Background Musics) and the game seemed to be working fine, until i tried to play the background sounds using the game jukebox. The list of songs just skipped forward from song to song, on and endless loop!

I’ve googled it and found almost nothing about this problem but at the end i’ve figured it out by trying to play the songs using the `play` command in the terminal. You need MIDI support to play those files! Apt-get to the rescue!

sudo apt-get install timidity

Just type this command into the terminal and the jukebox starts to work right away!

Happy TTD’ing!

No Comments