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!

3 Comments

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
~/.rvm/gems/ruby-1.8.7-p334\@mygemset/gems/mysql2-0.2.11
Hope it helps!

6 Comments

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!
end

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
end
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!"
end
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>"
   send_email(subject,to,from)
  end
  def send_purchase_mail
    subject = "Your purchase has been confirmed!"
    to = customer.email
    from = "Foo Sales <sales@foo.bar>"
    send_email(subject,to,from)
  end
end

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])
    end
  end    
 
  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
end

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!"
    end
  end
 
  create_mother_call_for :john
end
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!"
    end
  end
end
 
class Baby
  extend MotherCaller
  create_mother_call_for(:john)
end
 
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!

8 Comments

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)) }
  end
end

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
      subject.should_receive(:instance_variable_set).with(:zoo)
      subject.bar
    end
  end
end

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
      subject.stub(:instance_variable_set).as_null_object
      subject.should_receive(:instance_variable_set).with(:zoo)
      subject.bar
    end
  end
end

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.bar
      subject.instance_variable_get("@zoo").should == fake_random
    end
  end
end 

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!

5 Comments

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:

Kernel.should_receive(:open)

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!"
  end
end
# Expectations
describe MyTestClass do
  describe "#say_hi" do
    subject { MyTestClass.new }
    it "should say hi" do
      subject.should_receive(:puts).with("Hi!")
      subject.say_hi
    end
  end
end

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!

2 Comments

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
    ClassThatHasTheConstant.__send__(:remove_const,'Constant') 
    # 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
  end
  [ ... ] # your examples here
  after(:all) do
    ClassThatHasTheConstant.__send__(:remove_const,'Constant')
    ClassThatHasTheConstant.const_set('Constant', @old_constant)
  end
end

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