Archive for the ‘Tips’ Category

Nested Classes

You may already know this, but this is absolutely new to me. Yesterday a question suddenly popped up: “Can you put a class into a class?” I instantly hopped into irb (<3) and did this:

david@david-laptop:~$ irb
irb(main):001:0> class Foo
irb(main):002:1>   class Bar
irb(main):003:2>   end
irb(main):004:1> end
=> nil
irb(main):005:0> Foo.new
=> #<Foo:0xb77130b0>
irb(main):006:0> Foo::Bar.new
=> #<Foo::Bar:0xb770f960>

I’ve been wondering if this was possible before, but kind of assumed it wasn’t. But it is, and it’s just another example of Ruby’s awesometasticness. I’ll definitely use this, and I hope it’ll be useful for you too.

Conquer Trailing Whitespace

I’m an Ubuntu user and I love it. But: I don’t have TextMate so good old gedit has to suffice. One particular thing annoyed me, though. Say I have a controller that looks something like this:

class ForumsController < ApplicationController
  def new
    @forum = Forum.new
  end
end

What do I do when I want to add, e.g., a create action? I put my cursor after the end keyword for the new action, press enter, delete the two extra spaces (that gedit creates because auto-indentation is turned on) with Shift + Tab, press enter again and then Tab.

I do that a lot during a day. In my spec files things are even worse. Because of the nesting I have to tab in and out maybe eight times. That's genuine waste of time. If I had an awesome editor, things would be taken care of for me, but I don't. So what I did was to write a pre-commit hook for Git instead:

#!/usr/bin/env ruby

Dir["{app,config,features,lib,spec}/**/*"].each do |filename|
  unless File.directory?(filename)
    with_trailing_whitespace = File.read(filename)
    without_trailing_whitespace = with_trailing_whitespace.gsub(/ +$/, '')

    unless with_trailing_whitespace == without_trailing_whitespace
      File.open(filename, 'w') do |file|
        file.puts(without_trailing_whitespace)
      end

      `git add #{filename}`
    end
  end
end

Basically, what it does is to recursively loop through all files in the app, config, features, lib, and spec directories of my project. If there's any difference between the original version of a file with trailing whitespace and the one without, the script will update the file and add it to Git's index.

To install the hook, simply copy and paste the script into .git/hooks/pre-commit in any Git repository, chmod it to 0755 and you're off.

I still haven't found a way to maintain this behaviour throughout all my projects; adding a hook to one repository has no effect on others. Once that's done I have conquered the trailing whitespace!

What You Didn’t Know About Named Routes

In routes.rb, you can pass a named route to map.root. Here’s a quick example:

map.resources :people
map.root :new_person

Pretty neat, huh?