Monday, 3 March 2014

Context, Tooling and the Beginner Programmer

Renée De Voursney talking at the AU Ruby Conf about the trials and tribulations of learning Ruby.

Renée De Voursney - Teaching Ruby for fun and profit from Ruby Australia on Vimeo.

She talks about context and how there are so many disparate moving parts to get to grips with before one can "become" part of the Ruby community. Gaining a basic understanding of all the moving parts that encompass not only the Ruby language itself, but the social norms of RSpec, Git, Gems, Github, RVM, *nix, Macs, TDD and various command line tools, is too much of a hurdle for many people to jump.

The biggest problem with a complete novice trying to get into programming is always some sort of feedback loop that will give them the justification to carry on. I'm a great believer in learning by debugging, but at the same time, giving the novice quick wins is important. Get them up and running quickly from nothing (and I mean nothing - no tools installed on their machine yet) to "hello world" in ten minutes.

It's a difficult task. People have a variety of operating systems from various flavours of Windows through Linux boxes and OSX machines. Providing a generic one-size-fits-all is nigh on impossible. Fragmentation sets in. People blog about their frustration and put up tutorials that work on their uniquely configured environments. They try to find work-arounds to annoyances like not having admin rights on computers to circumventing firewall rules that seem to get in the way of any sort of gem installation. It isn't long before someone who just wanted to take Ruby or Rails for a quick ride is hitting their head against a brick wall. And the brick wall is usually just tooling.....it isn't even the code.

Friday, 21 December 2012

Poor man's guide to managing Ruby versions

Understanding the guts of Ruby Version Management by rolling your own

I've been tinkering with a fresh install of Ubuntu 12.10, setting up a nice clean development environment. One of the first things to do, of course, is implement some sort of Ruby version management. RVM and rbenv seem to be the clear winners in this arena, though there are a lot of tools out there that do a similar job.

Writing your own version management for your Rubies isn't actually all that difficult. At it's core, we need need two things:

  • A way to segregate the executables of the various versions
  • A way to call the versions at will

Segregating versions is trivial - working with files and folders, we can put the various versions into named directories.

Actually executing our different versions is not all that difficult either. One way would be to create aliases with version numbers and explicitly call those when we want to use them. The more popular way, however, is to manipulate our PATH variable. The PATH variable tells our operating system where to look for executables when we, for example, type a command into the terminal. The first match it hits is the one it uses.

Using this idea, it isn't all that difficult to set up our own poor man's Ruby version management.

But Why?

Why would anyone want to do this when there are already tested and stable versions out there?

Simple - because we can! Really, though, this is an experiment, a little tinkering that will further your own understanding and even if you don't actually use this for your own version management, it will give you a better appreciation of what's going on behind the scenes of your favourite Ruby environment management system.

Step 1 - Get and compile your rubies

To pull off this experiment, we are going to need two distinct versions of Ruby. I'm going to use a 1.9 and a 1.8. The advantage is it is easy to test which we have running with some simple Ruby string commands because of the changes between the versions.

Download Ruby 1.9.3-p327 and Ruby 1.8.7-p371. Now extract the archives:

$ tar -zxvf ruby-1.9.3-p327.tar.gz
$ tar -zxvf ruby-1.8.7-p371.tar.gz

Step 2 - Set up some directories

I'm going to create a directory called ".pmrbm" in which to stash my Ruby versions. Inside that directory, I'll create an explicit 1.8.7-p371 and 1.9.3-p327 directory:

$ mkdir -p $HOME/.pmrbm/1.8.7-p371
$ mkdir $HOME/.pmrbm/1.9.3-p327

Step 3 - Compile

Compiling Ruby from source might sound scary if you've never done it before, but really it's a walk in the park. We should have two directories in our downloads folder (from the unarchiving we did earlier) - one for the 1.8.7 and one for the 1.9.3 versions. As we compile our versions, we will pass in the path into which we want the compiled Ruby to end up with the "--prefix" command:

$ cd ruby-1.8.7-p371
$ ./configure --prefix=$HOME/.pmrbm/1.8.7-p371
$ make
$ make install

And you should have Ruby 1.8.7-p371 installed. Now we do the same for our 1.9.3-p327 version, but obviously substituting our 1.9.3 specific paths in:

$ cd ruby-1.9.3-p327
$ ./configure --prefix=$HOME/.pmrbm/1.9.3-p327
$ make
$ make install

We've now got two versions of Ruby compiled on our machine.

Win

How on earth are we going to use our Ruby versions? Well, if you are paranoid, you could cd into the various directories and confirm that Ruby is installed and running in those directories. I'll skip that step and simple start modifying my PATH. My system had a fresh install of Ubuntu on it, with no system Ruby installed, so at this point, even though I've compiled two different versions of Ruby, if I try to interrogate the version of Ruby on my system, I will get an error:

$ ruby -v
$ The program 'ruby' can be found in the following packages:
...

Obviously, I'm not going to install Ruby from apt-get, because that would defeat the object of this exercise. Instead, I'll type the following:

$ export PATH="$HOME/.pmrbm/1.8.7-p371/bin:$PATH"

And now when I can get the Ruby version (note I'm in my home directory, but you can be in any directory you want, the PATH will make sure that the OS can find your 1.8.7 version of Ruby:

$ ruby -v
$ ruby 1.8.7

If I run some code in irb, I can confirm that I'm running 1.8.7, because of the way it handles single string characters:

$ irb
> "cat[1]"
=> 97

Great, but what about 1.9.3? Easy as pie - simply change your PATH:

$ export PATH="$HOME/.pmrbm/1.9.3-p327/bin:$PATH"

Again, check the version and confirm with a little bit of single string manipulation:

$ ruby -v
$ ruby 1.9.3p327
$ irb
> "cat[1]"
=> "a"

Note that I was pretty sloppy there with the PATH. For example, if you were to examine your PATH variable at this point, you should see something like(your path will obviously vary based on your system setup):

$ echo $PATH
/home/rubyflewtoo/.pmrbm/1.9.3-p327/bin:/home/rubyflewtoo/.pmrbm/1.8.7-p371/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin/usr/bin:/sbin

See, both the ruby versions are present in the path, though at the moment, ruby is reporting it is version 1.9.3 because the first path that the OS finds Ruby in is 1.9.3-p327/bin, so it simply ignores the 1.8.7 path later in our environment variable. You can, if you feel like playing with this, move the 1.9.3 directory, and test again to see that the OS would then pick up the 1.8.7 version. So

$ mv ~/.pmrbm/1.9.3-p327 ~/.pmrbm/1.9.3-p327.back
$ export PATH=$PATH
$ ruby -v
ruby 1.8.7

Obviously, a neater solution would be to remove the portions of the PATH that are not needed rather than continually pre-pending to it

What now?

Now you should trash all of the above and go use one of the existing stable and actively maintained solutions. A few options:

Tuesday, 11 December 2012

Rails 3.2, MiniTest Spec and Capybara

What do you do when you love your spec testing with Capybara but you want to veer off the beaten path of Rspec and forge ahead into MiniTest waters? Follow along, and you'll have not one, but two working solutions.

The setup

Quickly now, let's throw together an app to test this out. I'm on rails 3.2.9.

$ rails new minicap

Edit the Gemfile to include a test and development block

group :development, :test do
  gem 'capybara'
  gem 'database_cleaner'
end

Note the inclusion of database_cleaner as per the capybara documentation

And bundle:

$ bundle

We will, of course, need something to test against, so for the sake of it, lets throw together a scaffold, migrate our database and prepare our test database all in one big lump. If you are unclear on any of this, go read the guides.

$ rails g scaffold Book name:string author:string
$ rake db:migrate
$ rake db:test:prepare

Make it minitest

To make rails use minitest, we simply add a require statement to our test_helper.rb:

require 'minitest/autorun'
require 'capybara/rails'

We can add in a quick integration test to verify that everything is working correctly up to this point:

$ touch test/integration/book_spec.rb

If you are that way inclined, you could create an "acceptance" directory and pop your tests in there instead. I'm not too bothered by the naming right now, because this is a proof of concept.

Now edit the book_spec.rb file we created

require 'test_helper'

describe Book do
  it "creates a new book" do
    1.must_equal 1
  end
end

Running this passes nicely:

$ ruby -Itest test/integration/book_spec.rb

Setup is complete. We have a nice little project with which to experiment.

Failing to use Capybara

At this point we can try to throw in some navigation from the Capybara DSL to see if it will work. Update book_spec to include "visit":

describe Book do
  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

and you will get an error when you run the test again - something to the effect of

$ NoMethodError: undefined method 'visit' for #<#:0x43c20f0>

Fix what you break

The rest of this post will focus on getting this small piece of code to work. I've found two ways so far. I'll present both and you can decide which you prefer.

The way of the Severed Rodent Hand

Pinched pretty much verbatim from the excellent rstat.us project, the Way of the Severed Rodent Hand uses a module. Working from the principle of the simplest thing that works, I'm going to start out in book_spec.rb and do this:

describe Book do
  Include Capybara::DSL
  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

This produces a passing test. Dig a little deeper though and we will notice that the Capybara documentation suggests using a teardown method to instruct DatabaseCleaner to clean our database as well as reset sessions. MiniTest supports teardown hooks, but we will use and after method to start with:

describe Book do
  Include Capybara::DSL
  after do
    DatabaseCleaner.clean       # Truncate the database
    Capybara.reset_sessions!    # Forget the (simulated) browser state
    Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
  end

  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

Our tests work - and everything is right with the world.

Sever

Of course, no self respecting rubyist is going to leave this code as it stands. As soon as we add another resource, we will be duplicating the after block. Instead, we are going to sever that code and create a module, just like rstat.us. I'm going to put this into my test_helper file for simplicity but on a larger project, you might prefer to use a dedicated integration_helper or acceptance_helper:

module IntegrationTestHelper
  include Capybara::DSL
  
  def teardown
    DatabaseCleaner.clean       # Truncate the database
    Capybara.reset_sessions!    # Forget the (simulated) browser state
    Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
  end
end

I've also taken the opportunity to move the code from "after" into a teardown hook - MiniTest will pick this up for us because it is just awesome! To complete this refactor, we must include our module into our spec. Open up book_spec again and change it a little:

describe Book do
  include IntegrationTestHelper

  it "creates a new book" do
    puts 'create'
    visit('/books/new')
    1.must_equal 1
  end
end

Our tests still pass. We are golden.

The Classical method

Using a module as we just did works well. Nothing to fix there. However there's a trade-off, we have that little "include IntegrationTestHelper" in all our test that need access to Capybara's DSL. We can swap out this inconvenience for a slightly different one - this one based on classes instead of modules. It has it's own inconvenience, but you pay's your money, you takes your choice.

Set up a class

This method relies on a class in our test_helper - let's code it up like this:

class IntegrationHelper < MiniTest::Spec
  include Capybara::DSL
 
  after do
    DatabaseCleaner.clean
    Capybara.reset_sessions!
    Capybara.use_default_driver
  end
end
MiniTest::Spec.register_spec_type( /Integration$/, IntegrationHelper )

The magic here is the last line - this basically says that for any test that is described as "Integration", set the parent to IntegrationHelper (and thus inherit all the goodness of the DSL and the after block). Of course this magic can only be hooked up if we change book_spec to include the word Integration in our initial describe:

describe 'Book Integration' do
  #include IntegrationTestHelper

  it "creates a new book" do
    visit('/books/new')
    1.must_equal 1
  end
end

This passes. Changing your register_spec_type regex to something like "/Integration$/i" and you will have a case insensitive match if you prefer to use normal english casing on subsequent words.

Wrap up

Two methods, both work. On the one hand, you have to "include", on the other hand you have to describe correctly but you get a class hierarchy. I know religious wars have been started over less, but I encourage you to try both and go with your gut. If you have a better/another way, drop me a comment and share the love.

Friday, 23 November 2012

Ruby, facemash and the Elo rating system via BDD

Reproducing the Elo rating algorithm in Ruby is a little challenge that I took upon myself recently for a small hack. The same Elo rating system that was scrawled upon the glass in "The Social Network" as the algorithm that Mark Zuckerberg used on rank people on FaceMash. As an exercise, here's a pass at it with a little BDD thrown in for good measure.

A new file - elo.rb:

require 'minitest/spec'
require 'minitest/autorun'


describe "result" do
  describe "when both players start with rating of 100 and k factor of 30"  do
    it "must return 115 for the winner" do
      new_rating.must_equal 115
    end
  end
end

Starting a new algorithm is always tricky. We know that the Elo rating system is essentially concerned with assigning ratings to players based on the outcome of their games or matches. In fact, it is widely used as a chess ranking algorithm. At a first glance then, I thought I might want to jump in and start modelling some objects - players, games, ratings, player ranking. But that sounds like a big bite. A lot can go wrong with hunches.....bunches of hunches and hunches in bunches.

Small steps then - what are we doing? The big picture. The major output we want is a new rating! Our first test tries to check that the new rating is equal to 115. Why 115? Because the excellent online elo calculator told me so when I typed a bunch of numbers in there.

The numbers

To get some numbers, I first read wikipedia's entry on the Elo rating system. The algorithm relies on each player having a rating, each game delivering a score to each player and the mysterious "k" value.

I decided, rather arbitrarily, to assume that in my two player match, each player starts with a rating of 100. We could, equally have started with 0, but 100 felt right. Similarly, each player starts with a k value of 30. Using any method you fancy (the aforementioned online elo calculator, or even, working it out by hand), a winner in the above scenario, would have a new rating of 115.

Of course, running our code fails miserably:

Loaded suite elo
Started
E
Finished in 0.001000 seconds.

  1) Error:
test_0001_must_return_115_for_the_winner(ResultSpec::WhenBothPlayersStartWithRatingOf100AndKFactorOf30Spec):
NameError: undefined local variable or method `new_rating' for #<ResultSpec::WhenBothPlayersStartWithRatingOf100AndKFactorOf30Spec:0x28a8830>
    elo.rb:8:in `block (3 levels) in <class:TestElo>'

1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

Test run options: --seed 62642

Player

We can get this to pass by declaring new_rating = 115. That would be very baby steps. I'm going to go a little faster. We are dealing with a "new rating". What has a rating? A player has a rating. Let's go with that for a moment and create a Player class.

class Player
  attr_accessor :rating
end

describe "result" do
  describe "when both players start with rating of 100 and k factor of 30"  do
    it "must return 115 for the winner" do
      winner = Player.new
      new_rating = winner.rating
      new_rating.must_equal 115
    end
  end
end

Run this and we still fail. However, we fail because our new rating is not 115 as we expect in our test.

  1) Failure:
test_0001_must_return_115_for_the_winner(result::when both players start with rating of 100 and k factor of 30) [elo.rb:19]:
Expected: 115
  Actual: nil

Getting rid of our nil is easy - we can define a new Player to default their rating to 100 if it isn't specified.

class Player
  attr_accessor :rating

  def initialize(rating=100)
    @rating = rating
  end
end

And our test starts to produce some more meaningful failure

  1) Failure:
test_0001_must_return_115_for_the_winner(result::when both players start with rating of 100 and k factor of 30) [elo.rb:19]:
Expected: 115
  Actual: 100

Current rating, New rating

Implied in all this Elo business is the idea that at some point, we will calculate the new rating based on a game between our players. To that end, we want the ability to update a player's rating based on a game outcome. That sounds like a pretty tall order. It starts me thinking towards game objects and....tooooooo complicated. Let's rather put some functionality into Player in the meantime - just to get it working.

class Player
  attr_accessor :rating

  def initialize(rating=100)
    @rating = rating
  end

  def calculate_new_rating
    @rating = 115
  end
end

describe "result" do
  describe "when both players start with rating of 100 and k factor of 30" do
    it "must return 115 for the winner" do
      winner = Player.new
      winner.calculate_new_rating
      new_rating = winner.rating
      new_rating.must_equal 115
    end
  end
end

Putting the above code together, our tests pass! Great - now all we have to do is write the code to actually do the calculation.

Calculating Elo

Looking back through Wikipedia and translating the algorithm into Ruby, we might end up with something like the following:

  def calculate_new_rating
    new_rating = rating + k_value * (score - expected_outcome)
  end

The k value, as we mentioned earlier, is going to be 30. Score is either 1 or 0 (win or lose - we ignore draws for now). That just leaves us with expected outcome.

Expected rating

We need to have expected outcome in place before we can calculate our actual new rating based on the outcome of our game. Time to code up the equation for expected outcome. I'm going to put it into Player for the moment. It might not actually belong there in the end, because an expected outcome sounds like something that should belong to a Game. But it is a start. Simply copying the formula from Wikipedia, we get the following piece of code:

  def expected_outcome
    1.0/(1 + 10**((opponent_rating - @rating)/400))
  end

Things to note

  • We are raising to a power - in Ruby we use ** to achieve this.
  • We need the opponent's rating
  • We should probably think about floating point arithmetic

We've meandered away from our tests at this point. Let's get back to them and start testing our expected outcome, we should have written this first really:

  describe "expected outcome" do
    it "must return 0.5 when ratings are equal"
      winner = Player.new
      winner.expected_outcome.must_equal 0.5
    end
  end

Even if you don't know the Elo algorithm inside and out - this makes sense - given two opponents who are the same level, the chances that one will win should be 0.5. The algorithm is fairly well documented though, and if you are inclined, you can hunt around and find tables of expected outcomes based on differences between opponent ratings. Running the above crashes - an undefined variable 'opponent_rating'. I'll make it a parameter

  def expected_outcome(opponent_rating)
  ....

Which gives us a wrong number of arguments error. We need to update our test and pass in an opponent rating

  describe "expected outcome" do
    it "must return 0.5 when ratings are equal"
      winner = Player.new
      winner.expected_outcome(100).must_equal 0.5
    end
  end

Passing tests. Good. Now we can flesh out that new rating algorithm. Feeling confident, I'm changing a fair amount in one go here, let's hope it works:

  def calculate_new_rating(score, opponent_rating)
    @rating = rating + 30* (score - expected_outcome(opponent_rating))
  end

and fixing our test

it "must return 115 for the winner" do
  winner = Player.new
  winner.calculate_new_rating(1, 100)
  new_rating = winner.rating
  new_rating.must_equal 115
end

Wow - it's good! Let's discuss the code a bit - I changed the calculate_new_rating method to take two parameters - a score and the opponent rating. Then I substituted 30 in for the k_value - at some point this should become a constant perhaps, or a parameter. I also set our rating instance variable upon calculating the new rating. This means that any time I call calculate_new_rating on a Player, it will update that player's rating to be their new rating. I guess I could start running around and adding in variables for current rating, old rating and such, but this feels a bit cleaner to me - you have a rating - as soon as a game is played, your rating should change to reflect that. I am passing in score - currently 1. In our implementation, it will only ever be 1 or 0 - games can be won or lost, and never tied (we are, after all, implementing a facemash like algorithm - there are no draws).

Improvements

This code is a first draft - a good working example - it has its drawbacks though, which become apparent when you start adding in more tests, and especially when you test the very real scenario of calculating the ratings of two players, one after the other. I'll leave you to play with it a bit and see if you can spot the gotchas. I'll pick it up again next time.

Monday, 12 November 2012

Stop asking for a ninja when you actually want a samurai

From the various appropriate entries on Wikipedia about ninja and samurai (emphasis mine)

A ninja or shinobi was a covert agent or mercenary. The functions of the ninja included espionage, sabotage, infiltration, and assassination
The shinobi proper, a specially trained group of spies and mercenaries
Samurai were the military nobility
Samurai felt that the path of the warrior was one of honor, emphasizing duty to one's master, and loyalty unto death

Now which one do you really want working for you?

Thursday, 8 November 2012

Overriding equality and Test Driven Development

Ruby has, at its root, an Object. Methods available in Object are available to every class because every class in Ruby inherits from Object somewhere in its own class hierarchy. Of course, you can override methods in subclasses, changing the functionality of a root method.

You might stumble on to this idea if you work through Test Driven Development By Example by Kent Beck, translating the Java code into Ruby as you go. At some point pretty early on, he overrides the equality method on the Currency class to better test if two instances are equal. I'm going to do the same here, working with Instruments instead of Currency.

Equality

Equality in Ruby can be expressed using any of the following three methods

object == other
equal?(other)
eql?(other)

These methods are defined on the base Object. The default implementation of equality will only return true if both objects are exactly the same. The interesting thing is that although these three methods start out functioning the same, the documentation does note the difference between them:

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality.

So we are encouraged to override == to test equality of our own classes and objects.

Instruments in irb

Let's put together a simple implementation to see how this works. Fire this up in irb:

class Instrument

  def play
    puts 'lovely sound'
  end

end

guitar = Instrument.new
=> #<Instrument:0x2a1b9d8>
another_guitar = Instrument.new
=> #<Instrument:0x2940c70>
guitar == another_guitar
=> false
guitar.equal?(another_guitar)
=> false
guitar.eql?(another_guitar)
=> false

You get the idea. The two guitars are not equal. Everything functions as per the documentation. Just for completeness, Ruby considers an object to be the same when it is *exactly* the same - keep typing:

third_guitar = guitar
=> #<Instrument:0x2a1b9d8>
third_guitar == guitar
=> true

That makes sense and behaves as per the documentation. Equality tests that the "actual" objects are equal. This is the equivalent of saying, in the real world, no two guitars are the same - even if they are both, for example, Ibanez Jems (see what I did there? ruby gems, guitar jems) with the Floral pattern that came off he production line one after the other.

Okay, the pedantic among you will argue that they won't be the same, the floral pattern will probably be a bit different - that was the point of Jems right? The tone might be a little different, the feel will be different - minutely different, but different none the less. Buuuuuut, I would argue, to all intents and purposes, these two fictional guitars are the same. They will have the same price tag, they will play pretty much identically (in double blind playing trials), they have the same number of pickups, same number of frets, same volume and tone potentiometer, same pickup-selector switch. They both have the same monkey handle, they will both produce the same note when tuned to A440.

The same

Given the above, for our example, we are going to say they *are* the same. In fact, to make it even simpler to show the code, I'm going specify that any 'guitar' is the same as any other 'guitar' (like Bruce Lee said "A kick is a kick, a punch is a punch").

To represent this in Ruby, we have to override object equality and put in its place, our own code to compare two instruments. That sounds a little scary to just bash out and I heard the word "specify" a few sentences ago, so I'm going to wire up some tests using the awesome minitest (last seen integrating into Rails) to help us code this and see where we get to.

Using various asserts included in our testing framework, we can test equality of objects because things like assert_equal actually just take the two objects and call the "==" method on those objects. Climb out of irb and create yourself a new file - I'm calling mine minstrel.rb:

require 'minitest/autorun'

class TestInstruments < MiniTest::Unit::TestCase

  def test_guitars_are_guitars
    guitar = Instrument.new
    another_guitar = Instrument.new
    assert_equal guitar, another_guitar, "guitars should be guitars"
  end

end

Pretty easy right? We require our minitest library and create a new class that inherits from MiniTest::Unit::TestCase - because that's how you use minitest :). Then we set up our first little test, create two guitars and try to test the assertion that they are equal. Running this, of course, fails miserably:

Started
E
Finished in 0.000000 seconds.

  1) Error:
test_guitars_are_guitars(TestInstruments):
NameError: uninitialized constant TestInstruments::Instrument
    minstrel.rb:10:in `test_guitars_are_guitars'

1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

And we can meander down a small intro to Test Driven Development if we fancy, but that's not really what I'm trying to show here. Instead, I'll just add our Instrument class that we played with in irb up above. A bit messy because I'm putting all my code in minstrel.rb....

require 'minitest/autorun'

class Instrument

  def play
    puts 'lovely note'
  end

end

class TestInstruments < MiniTest::Unit::TestCase

  def test_guitars_are_guitars
    guitar = Instrument.new
    another_guitar = Instrument.new
    assert_equal guitar, another_guitar, "guitars should be guitars"
  end

end

Now I can run the whole shebang again:

  1) Failure:
test_guitars_are_guitars(TestInstruments) [minstrel.rb:12]:
No visible difference.
You should look at your implementation of Instrument#==.
#

1 tests, 1 assertions, 1 failures, 0 errors, 0 skips

That' very interesting - look - it fails the assertion, but it actually tells us that there is no visible difference. Further, it points us nicely towards the method we should be examining which is, coincidentally, our equality on Instrument. Of course it is the equality method that is inherited from our base Object class, because as yet, we haven't defined an equality method explicitly.

Defining equality

At last we come to our point - how to override equality on our objects. Baby steps - I'm going to make my assertion pass by overriding equality in my Instrument class and always return true - not our final implementation, but, it is a start:

class Instrument
  
  def ==(other)
    true
  end

  def play
    puts 'lovely note'
  end

end

Running my tests now gives this output

# Running tests:

.

Finished tests in 0.000542s, 1845.7745 tests/s, 1845.7745 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips

Great success

We have successfully overridden our equality method. Of course our implementation is not complete - because any instrument will be considered equal to any other instrument at this point. One implementation is to expose an Instrument Type property on Instrument. Initialize any instance with a type and then test the types are the same for our equality. You might end up with something like this:

minstrel.rb:

require 'minitest/autorun'

class Instrument
  attr_reader :type

  def initialize(type)
    @type = type
  end

  def ==(other)
    @type == other.type
  end

  def play
    puts 'lovely note'
  end
end

class TestInstruments < MiniTest::Unit::TestCase

  def test_guitars_are_guitars
    guitar = Instrument.new('guitar')
    another_guitar = Instrument.new('guitar')
    assert_equal guitar, another_guitar, "guitars should be equal"
  end

  def test_guitars_are_not_violings
    guitar = Instrument.new('guitar')
    violin = Instrument.new('violin')
    refute_equal guitar, violin, "guitars should not be violins"
  end

end

All over overriding

That's it - we started out on a simple mission to override our method to test equality between classes, came up with a contrived example that differs from the standard Currency example in Kent Beck's book, and ended up with a little test suite toboot. The take home message - override equality by defining your own method called "==" with one param of (other).

Tuesday, 16 October 2012

Rails Callbacks and Boolean Values

Rails has a lovely feature as part of ActiveRecord - Callbacks; to wit:

Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state

Basically, that means that you can instruct Rails to execute your own code throughout the process of creating, updating and destroying objects/records. You can, for example, use them to set some default values on create, or perhaps do some last minute validation, or even fire an event just after you've saved a record. The available callbacks are:

  • after_initialize
  • after_find
  • after_touch
  • before_validation
  • after_validation
  • before_save
  • around_save
  • after_save
  • before_create
  • around_create
  • after_create
  • before_update
  • around_update
  • after_update
  • :before_destroy
  • around_destroy
  • after_destroy
  • after_commit
  • after_rollback

At the same time, Ruby methods have the concept of implicit return values. That is to say, any method will return the value of the last evaluated statement. This is neat - you don't need to write an explicit "return" at the end of your methods.

When we mangle these two features together, we can create subtle bugs in our code. Well not so subtle, because your code will just stop working the way you expect, and it can be fairly difficult to debug because no error is thrown.

Consider the Rails Callbacks again:

If a callback returns false, all the later callbacks and the associated action are cancelled

And I'm sure you'll see where I'm going with this now.....Take an example where you have a boolean value as one of your fields in your model. You want to set this boolean in a callback, either as a default value or because it represents some state based on some other logic.

Let's contrive an example - a blog application which allows comments. We want comments to be moderated of course, because spam is bad. We create a quick boolean on our comment model called "isinmoderation". Every time a new comment is submitted, we want to set this variable to true. We have an added piece of logic to trust any comments from readers who have submitted five good (non-spammy) comments.

Given the above, we might end up with something like the following:

class Comment < ActiveRecord::Base
  before_create :moderate

  protected
    def moderate
      unless is_from_trusted_reader
        this.isinmoderation = false
      end
    end
end

We run some tests and find that new comments from untrusted readers are not being saved to the database. We notice that our transaction is being rolled back, but there's no error. For a while, we are confused. And then we remember this blog post and realise that we are returning a falsey value from one of our callbacks....and, as the Rails docs say,

all the later callbacks and the associated action are cancelled

And the mystery is solved. So is there an elegant way to ensure we don't hit this condition? Well one way out is to explicitly declare a return of true from our moderate method. It is a little less elegant than the normal implicit return, but c'est la vie