Rubyconf India 2012

I just got back from Pune after attending the third Rubyconf India (well, that was last Monday; I managed to keep this post in drafts for a week), and – having attended all three conferences – I have to say, this conference keeps getting better every year.

For me, the highlights of this year’s Rubyconf were the keynotes by Charles Nutter and Mikel Lindsaar, Matz’s video keynote (obviously) and Steven Deobald’s Clojure talk. Mikel’s talk – How to Win – was especially inspiring and thought-provoking, particularly because I’ve just moved back to the startup world, having joined WowMakers just last month.

Another quite interesting talk was the one about data analysis from Chang Sau Sheong. The audience seemed very enthusiastic in this interactive talk. The talk about mobile platforms was also quite useful, since I’ve been looking at the available options over the past month. Apart from that, Aaron Patterson made a surprise appearance at Rubyconf in a short video message in Rocky Jaiswal and Arun Agarwal’s talk.

Having followed the recent discussion on Pat Shaugnessy’s post about the performance of Ruby strings of less than 23 characters, Niranjan Sarade’s talk about MRI internals was very appropriate for this year’s Rubyconf. I’ve been trying to work through Minero Aoki’s Ruby Hacking Guide and this covered some of the topics from the first few chapters.

One thing I noticed was that (unlike previous years) Rails related talks no longer dominate the conf. Instead, we had more variety in the topics covered, with talks covering JRuby, mobile platforms, data analysis, MRI internals, etc. I guess this is another indication that Ruby adoption is no longer just about Rails.

The inclusion of lightning talks was a great decision this year. There were talks that were interesting, informative and funny. Hopefully we’ll see more of these next year. (Psst… I hear it’s going to be Pune again in 2013.)

Global Day of Code Retreat, Chennai

I spend the day on Saturday at ThoughtWorks Chennai attending a code retreat. This is the first time I’ve attended a code retreat and I had a lot of fun at the event. This code retreat was organized in many different cities across the world as part of the Global Day of Code Retreat (Dec 3).

Code retreat is a day long event where you pair with different people for 45-minute sessions, trying to solve a problem (Conway’s Game of Life) using object oriented principles and test driven development. At the end of each session you delete the code, and start all over again with a different pair.

Session 1. For the first session, I paired with a Python developer but used Ruby and Rspec. Neither of us had spent much time doing test-first development, so we took some time getting used to writing tests before code. My pair didn’t know Ruby, so ping-pong programming didn’t work too well, but Ruby and Python are similar enough for us to not waste too much time on syntax.

We did make the mistake of spending too much time discussing the design in advance; we didn’t write the first few lines of code till almost 10 minutes into the session. At that time, I felt that thinking over the design in detail would help, but I have changed my mind since.

During the discussion after the session, Karthik Sirasanagandla, who was one of the facilitators, pointed out that we were doing TDD all wrong by planning too much in advance. I went through the next couple of sessions slightly skeptical about this idea… Knowing in advance exactly what your class is going to do will only help you write better tests, right?

Session 2. For this session, I paired with a Java developer, and we used Java and JUnit. I have to admit that after using Ruby for a while, statically typed languages seem like a lot less fun and we struggled to get much done.

Session 3. Once again I paired with a Java developer but we used Ruby and Rspec for coding. Rather than me writing all the code we tried another approach to pair programming. I would write some code, and slide the laptop to my pair who would write the next bit of code in Java-ish pseudocode, which I would then rewrite in Ruby, and then explain Ruby syntax. Once again, a lot of time was wasted on discussing syntax rather than on design.

Session 4. After lunch, I paired with another Ruby developer who I knew from the local Ruby user group. Now that language syntax was no longer a distraction, we had a very productive session.

For one, I got rid of the approach I had been using for the first three sessions – using an array of 1′s and 0′s to store the game state. Instead we started with the proper object oriented approach of using a Cell class to represent the state of each cell on the grid. We also switched to Test::Unit and Shoulda for the tests, rather than Rspec that I’d been using in the morning.

Session 5. Most of us were starting to get tired of the constant deleting of the code, and it wasn’t doing morale much good. So instead of having two more 45-minute sessions, we had a single longer session, so that people would have a chance to go further than they had in previous sessions. We also teamed up with our pair from the 4th session. We continued using Ruby but switched to Rspec for testing.

This was the session where I finally started getting the hang of test-first development. Unlike in the previous sessions, this time we strictly followed the principle of having a single failing spec, followed by code to make it pass, and then writing the next spec. We also didn’t spend too much time planning what attributes and methods a class would have and instead focused on what was the next method we needed to add to solve the problem.

Thoughts

One thing that surprised me was the number of developers from enterprise-y companies that turned up. (I too fall into that category.) The fact that very few people were Ruby (and Python) developers was quite surprising, seeing that the event was sponsored by ThoughtWorks and C42, which are both well known companies in the Ruby community.

Another surprise was how many of the people expected this to be some sort of a training session. I had expected most people participating in the code retreat to be people familiar with the format.

Conclusion

I can’t wait for the next chance to participate in a code retreat. It was a great experience pairing with other developers, but I felt that pairing programmers who code in different languages (and completely unfamiliar with each others’ preferred language) leads to time being wasted on understanding the syntax.

For pair programming to be effective, both people really need to code alternately, and therefore need to have at least one language in common. Hopefully there will be more code retreats organized and will have more people familiar with Ruby (or Python or JavaScript).

If there’s a code retreat happening in your city, don’t miss it. You’ll certainly pick up some fresh ideas about object oriented design.

Did you attend a code retreat in any of the cities on Dec 3? How did you feel about the event?

Writing Ruby Gems – Part 4: Setting up Test::Unit

[This is the 4th part of a series of posts about writing a Ruby gem. The introductory post about this tutorial contains links to each part of the tutorial. Previous post - Publishing to Rubygems.org.]

So far in this tutorial we haven’t written any code that would be useful in solving Sudoku. The reason is that I didn’t want to start writing any code until we have a test framework set up for testing our code.

Test::Unit is the unit testing framework that ships with Ruby, so we will first set up our gem to run unit tests with the “rake test” command. However, I prefer another testing framework, Rspec, for writing the tests. (We’ll set up Rspec in the next part of the tutorial and then continue using that rather than Test::Unit for testing.)

We will write a simple method in the sudoku module that will return a string “Sudoku: version 0.0.0” (the version number will obviously have to be taken from lib/sudoku/version.rb).

We will put all our unit tests in a directory called test. We will now add a rake task called “test” to run all the unit tests. To create this, we will first need to create a Rakefile that looks like this:

require 'rake/testtask'

Rake::TestTask.new do |t|
 t.libs << 'test'
end

desc "Run tests"
task :default => :test

Rake already provides a task called test, so we are making use of that and have configured the task to use the test/ directory with t.libs << 'test'. We will also configure rake to make the test task the default when rake is run. Running “rake” without a task name would now be the same as running “rake test”. (In the next post, we’ll change this to run our Rspec specs rather than the unit tests.)

Now let’s add a test file test/test_sudoku.rb and add a silly test that we know will fail.

require 'test/unit'
require 'sudoku'

class TestSudoku < Test::Unit::TestCase
  def test_silly_example
    assert_equal 2+2, 5
  end
end

2+2 isn’t equal to 5, so this test should fail. Run the rake task:

$ rake test
Loaded suite /home/nithin/.rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2/lib/rake/rake_test_loader
Started
F
Finished in 0.000950 seconds.

 1) Failure:
test_silly_example(TestSudoku) [/home/nithin/work/sudoku/test/test_sudoku.rb:7]:
<4> expected but was <5>.

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

Test run options: --seed 21001
rake aborted!
Command failed with status (1): [/home/nithin/.rvm/rubies/ruby-1.9.2-p180/b...]

Tasks: TOP => test
(See full trace by running task with --trace)

Now change the assertion to make the the test pass.

$ rake test
Loaded suite /home/user/.rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2/lib/rake/rake_test_loader
Started
.
Finished in 0.000544 seconds.

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

Test run options: --seed 23369

If you try running rake without the task name, you will see that the output is exactly the same.

Now let’s remove the silly test and write a test that acually tests the version_string method that we’re adding.

  def test_version_string
    assert_equal Sudoku.version_string, "Sudoku version #{Sudoku::VERSION}"
  end

Now if you run rake you will get an error with the message: “NameError: uninitialized constant TestSudoku::Sudoku”. To fix this, we need to add the code for the version_string method in lib/sudoku.rb.

require 'sudoku/version'

module Sudoku
  def self.version_string
    "Sudoku version #{Sudoku::VERSION}"
  end
end

Now rake will run the test successfully. Let’s rebuild our gem and install it with the generated sudoku-0.0.0.gem file to see that it installs correctly.

However, we’re not done yet. If you check the gem directory in the gem installation path, you will see that our test/ directory is missing. To tell rubygems to include that code in the package, we’ll add the following line in the gemspec:

Gem::Specification.new do |s|
  # other stuff
  s.test_files  = Dir.glob("test/**/*.rb")
end

Rebuild and install the gem again and you’ll see the test directory in the installed gem path.

In the next part of the tutorial we’ll set up rspec for testing the gem and along with that start adding some real code for the sudoku solver.

[Subscribe to this blog to find out when the next part of this tutorial is published, or keep an eye on the first post in this series where I'll post the links to all published posts.]

Writing Ruby Gems – Part 2: Adding some code

[This is a part of a series of posts about writing a Ruby gem. The introductory post about this tutorial contains links to each part of the tutorial. Previous post - Gem specifications.]

In the previous post, we saw how to set up the gemspec and also installed the empty gem into our rubygems directory. Now it’s time we started adding some code to our gem.

Create a directory called lib/ and save a file sudoku.rb with the following code:

module Sudoku
 # hopefully someday this module will solve Sudoku.
end

It’s not much code, and it doesn’t do much, but we have to start somewhere. Now build and install the gem as we did in the previous part of this tutorial:

$ gem build sudoku.gemspec
$ gem install sudoku-0.0.0.gem

If you check the installation path for your gem in the rubygems folder, you will still find it empty. This is because rubygems doesn’t know what files to package into our gem. To fix that, let’s tell the gemspec what files need to be added.

Gem::Specification.new do |s|
 # rest of the stuff
 s.files = Dir.glob(“lib/**/*.rb”)
end

Build and install the gem again, and this time you’ll find lib/sudoku.rb in the gem installation directory.

Gem authors often use a version.rb file to store the version information. It’s always prudent to use a separate directory within the lib directory to put your code. This is because require 'yourgem' causes rubygems to add your gem’s lib/ to the load path. Now every require statement will also look at the files in your lib/ and it’s possible that the names might clash with some other gem.

The convention is to have a directory within lib/ with the same name as the gem. This way only sudoku.rb will be loaded from the load path and we can safely require 'sudoku/version' within sudoku.rb to access version.rb.

We’ll add version.rb in lib/sudoku and we should now have a gem directory structure that looks like this:

sudoku
├── lib
│   ├── sudoku
│   │   └── version.rb
│   └── sudoku.rb
└── sudoku.gemspec

Let’s now add the version information in version.rb:

module Sudoku.
  VERSION = '0.0.0'
end

And now use this in the gemspec by using Sudoku::VERSION instead of using the string “0.0.0” directly.

$LOAD_PATH.push File.expand_path("../lib", __FILE__)
require 'sudoku/version'

Gem::Specification.new do |s|
  s.name        = "sudoku"
  s.version     = Sudoku::VERSION
  # .. other stuff
end

The first line adds the lib/ directory of your gem to ruby’s load path, so you can include the files within that directory relative to your load path. For instance require 'sudoku' would load lib/sudoku.rb. Here we need the version.rb file for accessing Sudoku::VERSION constant, so we use require 'sudoku/version' to add lib/sudoku/version.rb.

As you may have noticed, we’re still not any closer to having a working sudoku solver, but we’ve learned a lot about how to create a bare gem and organize the files within it.

Don’t worry, we’ll eventually get to writing the actual sudoku solver. In the meanwhile, we’ll also look at publishing our awesome gem to rubygems.org and setting up tests using Test::Unit and Rspec in the next 2-3 posts.

[Subscribe to this blog to find out when the next part of this tutorial is published, or keep an eye on the first post in this series where I'll post the links to all published posts.]

Writing Ruby Gems – Part 1: Gem specifications

[This is the first part of a series of posts about writing a Ruby gem. The introductory post about this tutorial contains links to each part of the tutorial. Next post: Adding some code.]

The first thing to do when creating a new gem is to create a file called gemspec that contains information about the gem. The gemspec file will have the name of your gem, ie. my gemspec will be called yourgemname.gemspec.

(Once again, I’d recommend naming your gem something other than “sudoku” since that name is already taken and you’ll not be able to share your awesome gem on rubygems.org. For the rest of the post, I’ll use the name sudoku for the gem, and you will have to replace it as required.)

Create a directory for your sudoku solver gem and add a gemspec file. In your gemspec file, add the following code, replacing the values for name, authors, email and homepage:

Gem::Specification.new do |s|
 s.name        = "sudoku"
 s.version     = '0.0.0'
 s.authors     = ["Nithin Bekal"]
 s.email       = ["me@nithinbekal.com"]

 s.summary     = "Sudoku solver in Ruby"
 s.description = "Solves Sudoku puzzles. D'uh!"
 s.homepage    = "http://github.com/nithinbekal/sudoku"
end

Now that you’ve written the gemspec, build the gem using the “gem build” command:

$ gem build sudoku.gemspec
 Successfully built RubyGem
 Name: sudoku
 Version: 0.0.0
 File: sudoku-0.0.0.gem

This command will package your gem project into a gem file that can be used to install the gem. This file will have the structure gem_name-version.gem (with the gem name and version coming from the gemspec). Our sudoku gem is at version 0.0.0, so the gem file will have the name sudoku-0.0.0.gem. You can use this file to install the gem for your ruby installation with “gem install sudoku-0.0.0.gem”.

$ gem install sudoku-0.0.0.gem
Successfully installed sudoku-0.0.0
1 gem installed
Installing ri documentation for sudoku-0.0.0...
Installing RDoc documentation for sudoku-0.0.0...

You can check that the gem is available by doing:

$ gem list | grep sudoku
sudoku (0.0.0)

If you check the gem installation folder for the gem and you’ll see that there are no files in it. To find the location where the gem will be installed, do “gem env” on the terminal:

$ gem env
RubyGems Environment:
 - RUBYGEMS VERSION: 1.8.5
 - RUBY VERSION: 1.9.2 (2011-02-18 patchlevel 180) [i686-linux]
 - INSTALLATION DIRECTORY: /home/username/.rvm/gems/ruby-1.9.2-p180
 - RUBY EXECUTABLE: /home/username/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
 - EXECUTABLE DIRECTORY: /home/username/.rvm/gems/ruby-1.9.2-p180/bin
 - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
 - GEM PATHS:
    - /home/username/.rvm/gems/ruby-1.9.2-p180
    - /home/username/.rvm/gems/ruby-1.9.2-p180@global
 - GEM CONFIGURATION:
    - :update_sources => true
    - :verbose => true
    - :benchmark => false
    - :backtrace => false
    - :bulk_threshold => 1000
 - REMOTE SOURCES:
    - http://rubygems.org/

Go to the path shown as INSTALLATION DIRECTORY, and within that navigate to gems directory. Here, you will find your new sudoku gem in the directory sudoku-0.0.1. This directory will be empty now because we haven’t yet written any code for our awesome sudoku solver.

Now that we have created a gemspec, used it to build our (empty) gem and even installed it, you can sit back for a few minutes and bask in the glory of your awesome new gem. (Let’s ignore the fact for now that it does absolutely nothing. After all, eventually our gem will be able to solve any sudoku you throw at it.)

In the next post, we’ll look at the next few steps in writing our gem – adding a lib directory that contains all the logic and some source files for our gem.

[Subscribe to this blog to find out when the next part of this tutorial is published, or keep an eye on the first post in this series where I'll post the links to all published posts.]

Writing Ruby Gems

Creating a Ruby gem is a lot easier than it seems. Many tutorials about writing gems recommend using something like Jeweler or Hoe to create the structure of the gem for you.

Using such tools will make it much easier to get started with a gem, but building a gem from scratch will help you figure out how exactly those tools organize your gem’s structure. Here, we will walk through creating a gem from scratch, without generating any code.

The gem we are creating here is called sudoku, and it is supposed to be able to solve… er… sudoku puzzles. But this tutorial isn’t about creating a sudoku solver, so we’ll not worry too much about the logic that goes into a sudoku solver and instead focus on how we will package our gem.

The gem name sudoku is obviously taken (by me) and you can’t publish the gem to rubygems.org with the same name. (We will look at how to host the gems at rubygems.org in a future post.) I will be using the name sudoku for our gem in the rest of the tutorial, but you can use some other gem name (sudoku-yourname, perhaps?) and replace “sudoku” by your gem’s name wherever applicable.

The actual tutorial is split into several posts, each covering one small step in writing the gem. Here are the links:

1. Gem specifications
2. Adding some code
3. Publishing to rubygems.org
4. Setting up Test::Unit
5. Setting up Rspec

I’ll hopefully add more posts to this series in the coming days. These are some of the ideas for topics I’ll write about:

6. Adding an executable
7. C extensions in Gems
8. More on organizing the code
9. Gem version numbers

I’ve pushed the code for this project to github, so you can take a look at the latest code there.

[Subscribe to this blog to see when new posts are added to this series, or keep an eye on this page. You can also browse the Ruby related posts on this blog or browse my Delicious bookmarks related to rubygems.]

Rubyconf India 2011 – Live Blog

I haven’t been able to post updates here regularly enough on the afternoon day 1, so I don’t think there’s much point in having a separate post for day 2. I’ll be posting updates from day 2 here and this time I’ll post reverse chronologically.

Day 2

5.00pm Nick Sieger is about to present the closing keynote: Happiness : Ruby :: Freedom : JRuby.

3.45pm. Having been treated with lots of code on all slides today, feeling a bit awkward sitting at the talk on Software Quality and Test Strategies for Ruby and Rails Applications, which is somewhat less technical.

3.00pm. The first talk of the afternoon was “But the Language Supports It” by the folks from C42.in, Niranjan Paranjape and Aakash Dharmadhikari. They made a few controversial suggestions about some features of Ruby, such as avoiding hash arguments and even switch statements (or I badly misunderstood what they were suggesting.)

Now off to “Software Quality and Test Strategies for Ruby and Rails Applications” by Bhavin Javia.

The Brian and Srushti show at Rubyconf India 2011.

1.00pm. Brian Guthrie and Srushti were absolutely brilliant at the talk about Continuous Delivery in Ruby. Brian had the audience laughing every minute of the talk with his “I write perfect code; I don’t need tests” gags. One of the best (and most entertaining) talks at this Rubyconf.

11.45am Excellent presentation of CoffeeScript by Nicolas Sanguinetti. Loved the slides, and I’m waiting to see the slides uploaded.

Nicolas Sanguinetti at Rubyconf India 2011: "Let's have a Cup of Coffeescript"

11.00am. Nicolas Sanguinetti – Let’s have a cup of Coffeescript.

10.45am. Very geeky keynote from Ola, with lots of code in almost every slide, and yet it wasn’t all that difficult to follow. Interestingly, Ola suggests that removing features from the language could make it better. Some quotes (slightly paraphrased, because couldn’t type them down in time.):

- Java would be a much better language if Oracle could remove some features from the language.

- I think that monkey patching [in Ruby] is fantastic.

- Ruby is a better choice as an enterprise language than Java because it’s easier to add business features quickly.

10.00am. Ola Bini’s keynote – “The Good, the Bad and the Ugly.”

Ola Bini keynote at Rubyconf India 2011

Day 1

6.00pm. Inspiring keynote over video by Chad Fowler about Service.

Chad Fowler video keynote at Rubyconf India 2011

5.00pm. Couldn’t blog anything in the afternoon. A couple of great talks in the afternoon – “I can haz HTTP” by Sidu Ponnappa and Niranjan Paranjape, and “Writing Compilers the Easy Way” by Vishnu Gopal.

1.45pm. Sitting on the back row at Karthik Sirasanagandla’s talk about Ruby object model. This talk seems to be aimed at newcomers to Ruby. Nick Sieger is speaking on the other track about Refactoring a Legacy Java Application to Rails. My phobia of legacy apps dragged me out of there. Am I missing an awesome talk? Based on the reactions on twitter, I believe I am.

1.00pm. Brian Guthrie didn’t disappoint. As funny as last year, and lots of code examples. His quote “Humor is hard, guys!” beating all the other jokes he made today.

He also shared his super secret recipe to learning Ruby. I’ll ignore his specific request to the audience not to share i and put it up here anyway. ;-)

1. Read Ruby code.
1a. Read good Ruby code.
2. Write Ruby code.
2a. Step outside Rails.

Really wish the talk on Backbone.js hadn’t overlapped. Very interested stuff, and something I’d love to try sometime soon. But after being at Brian Guthrie’s talk last year (especially because of the multi-colored slides screaming out “TEST! TEST! TEST!”… remember that one?) I really couldn’t choose and had to pick one randomly. I hope this year the organizers will upload the videos of all the talks.

Brian Guthrie at Rubyconf India 2011

11.25am. Couldn’t pick between Brian Guthrie and Prateek Dayal’s talks next. Had to do ruby -e “puts rand(2)” to decide. Ruby picked Brian’s talk. ;-)

11.10am.

“The most important thing about a language is the community. We have to keep being nice.” – Matz

11.15am. Curation of technology is key to survive in the technology race, says Matz.

11.02am. ZOMG! MATZ VIDEO KEYNOTE!!! – “Why Ruby Again”.

“We as a community are nice to each other. That’s Ruby’s greatest property.” – Matz.

Yehuda Katz at Rubyconf India 2011

11.00am. Yehuda: “ActiveResource in Rails should have less configuration, more convention.” Convention doesn’t really exist at the moment, does it?

10.20am. Some hilarious quips from Yehuda about X-UA-Compatible header for IE9.

Btw, in case you haven’t come across this, take a look at this app to find fellow hackers at Rubyconf.

10.05am. Yehuda Katz keynote about to start.

10.00am. Rohit Bansal from Thoughtworks kicks off Rubyconf India 2011.

Building community is key for clients to accept Ruby based apps in proposed solutions – Rohit Bansal

9.40am. I can recognize Ola Bini in the front row. (Is that Nick Sieger next to him?) Waiting for Yehuda Katz’s keynote at 10 – Building Rails Apps for the Rich Client, and that will be followed by Matz’s video keynote Why Ruby Again.

9.15am. Just reached the Royal Orchid hotel in Bangalore and caught up with the rest of (current and former) Foradians. Looking forward to the conf to kick off at 10am. Not sure if I’ll be able to do a proper live blog. I’ll try.

Review: The Rails 3 Way (Obie Fernandez)

Often enough in the Rails community you hear people saying that following the Rails way of doing things will make life much easier. As the title suggests, this is the book that teaches you how to develop Rails 3 applications in “the Rails way”.

This book is not for beginners. Readers should at least know how Rails works, and preferably even have developed one or two applications as well. The book is organized in the form of a reference, and so if you’re looking for a step by step tutorial, you will be disappointed.

On the other hand, readers who already can develop Rails applications would find this a very interesting book to read. I wasn’t expecting that I would be able to read this book from beginning to end, but I did manage that, although with the amount of information in the book, I can hardly remember a tenth of what I read.

Like Rails, this book is highly opinionated. You will be told that Rspec is the Rails way to test, and that Haml is the Rails way of writing templates, even though Test::Unit and erb templates are the Rails default. In fact, there’s an entire chapter dedicated to Rspec and all the view examples use Haml and not erb. Those who use erb for templates might find the Haml examples a tad distracting.

The content of the book is arranged like this:

The first chapter discusses Rails configurations (bundler, dveleopment/test/production environment etc.) and is followed by a chapter on routing. It’s mostly plain reference so far, telling you what and how Rails works and how to set up your application. The third chapter, on REST and its implementation in Rails, is where this book really started getting my attention. This chapter will tell you all you need to know about why REST is such a big deal in Rails.

Chapters 4 through 9 cover the M and C of Rails MVC — the models and the controllers. ActiveRecord is covered in great depth and the chapter on advanced ActiveRecord is amazing. Reading the section on single table inheritance left me despairing about the awkward ways in which I used to handle ActiveRecord objects that would have been better off being split off into subclasses referring to the same table.

Chapters 10-12 cover the V of MVC – the views and helpers and a chapter on Ajax on Rails. This part too is one that you might use more as a reference than as read-on-the-train-to-work material. Especially the chapter on helpers is rather dry, and Obie himself mentions that it is reference material. In fact, the different helper modules are even arranged alphabetically.

Chapter 13 is on sessions management, and is followed by a chapter covering Authlogic and Devise – the two most popular authentication plugins for Rails. Since Rails doesn’t have a built in authentication system, a quick look at the two most popular plugins makes a lot of sense.

Chapters 15-16 cover ActiveResource and ActionMailer respectively. Frankly, I never really got what ActiveResource is all about, and I’m afraid I still haven’t got the eureka moment after reading this book.

These are followed by a chapter on caching and performance, and one on the testing framework, Rspec — both incredibly useful chapters. The former explains how to use builtin mechanisms in Rails to improve performance and the latter gives a quick introduction to Rspec. Chapter 19 covers Rails plugins and chapter 20 is about background processing in Rails – specifically Delayed Job, Resque, and rails runner.

This 700+ page book covers the Rails framework comprehensively (although it does skip ERB and Test::Unit completely). Like its predecessor The Rails Way for earlier versions of Rails, this book will be one that you will find most Rails developers referring to and quoting over the next few years.

Are there any negatives about this book? I should point out once again that this is mainly a reference for the framework, so some chapters might seem dry if you’re reading cover to cover. (I should also point out that these are the very chapters that you will be turning to when you desperately need reference for how to do something.) For instance, the chapter on helpers should certainly have been cut short and the majority of the content moved to the appendix. But on the whole, I have very few complaints about the book.

So who should buy this book? If you’re completely new to Rails, don’t buy now. (Or better, buy it but read it after you’ve read an introductory book on Rails.) Newcomers will easily be overwhelmed with the in-depth coverage of Rails and the lack of example apps to work on while learning.

That doesn’t mean that beginner level Rails programmers won’t find this book useful. I’m only saying that this wouldn’t be the best book when you’re looking at Rails for the first time. If you have some understanding of Rails, even if it is only one or two toy apps, this book will help you make big leaps in productivity. And experienced Rails programmers will obviously find the exhaustive coverage of Rails very useful.

Review: Eloquent Ruby (Russ Olsen)

If you are new to Ruby programming, Eloquent Ruby should be the book you read right after you finish your introductory Ruby book. It’s not a beginner’s tutorial, but with a little background on Ruby, it would be easy to follow.

This is one of the better programming books I’ve read. It has plenty of short and clear example code snippets, a very conversational and humorous writing style and most importantly, covers exactly the kind of topics a newbie should understand about Ruby.

The book is divided into 4 parts – (1) The Basics, (2) Classes, Modules and Blocks, (3) Metaprogramming (4) Pulling It All Together.

The firsts section covers the basic Ruby idioms in a way that you wouldn’t normally get to read in most books. It has chapters like “Choosing the Right Control Structure”, “Write Specs”, “Embrace Dynamic Typing”.

The second section — the most useful one, in my opinion — covers classes, modules and blocks with chapters like “Use Class Instance Variables”, “Use Blocks to Iterate” and “Use Modules as Name Spaces”. This section does an excellent job of explaining how to effectively use blocks, which are probably Ruby’s most useful feature.

The third section talks quite a lot about using, and of not misusing, the powerful method_missing method. Other Ruby metaprogramming topics such as monkey-patching are also covered.

The final section talks about one of Ruby’s greatest strengths — building DSLs — and also about creating and packaging gems. The book wraps up with a quick note on the the available ruby implementations.

At the end of each chapter there is a section “In the Wild” where the author points to real world code relevant to that chapter. Knowing where to look for real world examples will be especially useful for newbies who haven’t read a lot of other people’s code.

Another useful section in each chapter is “Staying Out of Trouble”, where the author explains the common pitfalls associated with the topic being discussed.

The examples that are used in the book make it extremely easy to understand. I often find books choosing overly elaborate examples and thereby distracting readers away from the language idiom being discussed. Eloquent Ruby doesn’t have that problem. The author starts with a simple Document class and uses the same example throughout the book, making it easy to focus on the idiom being discussed.

There are no real negatives I can point out, except for the slightly outdated chapter on packaging gems. However, I was reading the Safari’s Rough Cuts edition of the book, and it’s a work in progress, so it might get updated soon enough.

This book is a must read if you are a beginner to intermediate level Ruby programmer. It teaches the Ruby way of writing code, and answers many of the questions that one might have on the effective use of Ruby idioms.

You can read the Rough Cuts edition on Safari Books online.

Using Haml with Rails

I have always used erb for my Rails templates, but today I decided to try HAML. I was pleasantly surprised by how little work there is to get it to work.

First add the following line to the Gemfile and run bundle install.

gem 'haml'

Let’s suppose this is the ERB code for the application layout – app/views/layouts/application.html.erb.

<!DOCTYPE html>
<html>
<head>
  <title>Hello!</title>
</head>
<body>
  <div id="wrapper">
    <%= yield %>
  </div>
</body>
</html>

Let’s convert that ERB to HAML: (app/views/layouts/application.html.haml)

!!! html5
%html
  %head
    %title Hello!
  %body
    #wrapper
      = yield

Let’s create a home page that says “Hello, world”. Put this code in app/views/pages/home.html.haml.

%p Hello, World!

Now if you start up the rails server, Rails will render the following HTML for /pages/home.

<!DOCTYPE html>
<html>
  <head>
    <title>Hello!</title>
  </head>
  <body>
    <div id="wrapper">
      <p>Hello, world!<p>
    </div>
  </body>
</html>

There you go. HAML with Rails in 2 minutes. That YAML/Python-esque syntax will take some time to get used to, but it’s definitely very concise. I’m really looking forward to using it in my next project (or whatever toy app I build next).

What do you use for your Rails templates? HAML? Plain ‘ol ERB? Something else? Which do you think is the best and why?