Category: Rails

  • Let the Conf begin

    I just arrived in Portland a few hours ago for RailsConf ’07. I’m looking forward to attending the tutorial sessions tomorrow, not to mention watching presentations by fellow Rails geeks on Friday and Saturday. My own talk on homesteading and Teascript will be given on Saturday at 10:45 AM for those who are interested. Hope to see you there!

  • Creating service apps with Rails at tonight’s Ruby meetup

    This is another brief reminder that I’ll be giving a preview of my RailsConf talk at tonight’s Ruby meetup. The meetup starts at 7 PM at Red Hat headquarters. Hope to see you there!

  • Preview my RailsConf talk at this month’s Ruby meetup

    For those who live in the RTP area, I’ll be giving a preview of my RailsConf talk at the Raleigh-area Ruby Brigade meetup on April 17th. We meet at Red Hat headquarters on NCSU’s Centennial Campus at 7:00 PM. I’ll be talking about Teascript, homesteading, and building niche web apps that generate passive income. The talk is pretty solid, but I’ll still be asking for feedback from the group on what can be added or improved. See you there!

  • Turn finders into associations and get caching for free

    Let’s say we have a method on a model that looks something like this:

    def last_assignment
      assignments.find(:first, : order => 'created_at DESC')
    end
    

    We call this method several dozen times from various other methods on the model. The problem is, every time we call the method a new database query is triggered. This happens even if we make multiple calls within the same method. For example:

    def last_assignment_is_old?
      last_assignment && last_assignment.completed_at && last_assignment.completed_at < 30.days.ago
    end
    

    This results in three identical queries to the database. How wasteful! Let's fix it:

    def last_assignment
      @last_assignment ||= assignments.find(:first, : order => "created_at DESC")
    end
    

    Ahhhh, this is much better. Now we're storing the result as an instance variable on the model. Our last_assignment_is_old? method will only trigger a single call to the database now since we're caching the result. But what happens if we do something like this?

    puts model.last_assignment.nil?
    model.assignments.clear
    puts model.last_assignment.nil?
    

    On the console, we should see false and then true, right? What we actually see is false and false. Even though we clear out the assignments from the model, the last assignment is still stored in the @last_assignment instance variable. Since we're dealing with the same instance of the model, the cached value is returned. In this particular case, that's not good!

    The way to get around this is by using an association:

    has_one :last_assignment, :class_name => "Assignment", : order => "created_at DESC"
    

    This association basically says, "Sort the assignments by the creation date and give me the first one in the list." After running our test code again, we're golden. It turns out that Rails' associations provide caching automatically. All we have to do is remember to call reload on our model before querying it again. This will ensure that we're working with fresh data:

    puts model.last_assignment.nil?
    model.assignments.clear
    puts model.reload.last_assignment.nil?
    

    Now we get false and then true as expected. The reload trick won't work with instance variable caching, unfortunately, which is why the association is a better choice in this case.

    After examining a few more of our models, we discover that there are many such finder methods that can be converted to associations. We quickly begin converting them, hoping nobody notices that we've been senselessly operating without freebie caching for so long.

  • Multiparameter assignment validation

    Have you ever realized that the default Rails date helpers allow invalid dates to be selected? I ran into an issue yesterday where one of my Teascript users attempted to select a date of November 31, 2007. That date obviously doesn’t exist. Instead of failing with a validation error, however, Rails threw a MultiparameterAssignmentErrors exception.

    This is the first time I’ve run into this particular problem in Rails, and I’ve been using the framework for over two years now. Suffice it to say the odds of running into it are slim, but how should it be handled once it occurs? I found a clean, if not particularly elegant, solution in the Validates Multiparameter Assignments plugin. Once the plugin is installed, adding a single line to your model is all that’s required:

    class User < ActiveRecord::Base
      validates_multiparameter_assignments
    end
    

    The plugin causes any multiparameter assignment exceptions to be surfaced as validation errors, which is exactly what I needed to happen. Why don't I think it's elegant? Simply because it takes the shotgun approach by assuming that I want to validate all multiparameter attributes. I'd prefer to specify which attributes I want validated. This is a minor nit, though. The plugin does work quite well.

    There is one other customization that can be made to the plugin, but I've got to leave some surprises for you so check out the wiki page to familiarize yourself with the plugin. If you don't need the plugin now, I can pretty much guarantee you'll need it eventually.

    Update: This plugin is unnecessary as of Rails 2.0.2 because invalid dates are now gracefully offset to the next valid day without causing a validation error.

  • Rails in the Enterprise

    Tim O’Brien recently cataloged the top four myths that often prevent Rails from being used in Enterprise settings. From performance to flexibility, he does a thorough job covering many the objections that I’ve heard raised myself when proposing Rails as a possible solution. It can be frustrating to be in that situation, but Tim provides some “real answers” that you can fire back when challenged. This is a fascinating read, even for someone who isn’t plugged in to a large corporation right now.

  • RubyConf in the southeast

    The Ruby community in the Research Triangle Park area of North Carolina has been growing by leaps and bounds lately, in large part due to the fantastic job Nathaniel Talbott has been doing with the local Ruby Brigade. Another sign of the growing interest in Ruby and Rails in the area is the just-announced Ruby Hoedown, a RubyConf of sorts that’s being hosted by the Brigade in the Raleigh area on August 10th and 11th. Details are sketchy, but you can register on the site to receive more information as it becomes available. And to all you aspiring speakers, now is the time to start thinking about what you’d like to present at the conference!

  • Highrise is now taking leases

    37 Signals’ latest web application, Highrise, is now open for business. They offer a free account so you can try out the service without laying down any dinero. Looks like a useful tool. It’ll be interesting to see how tightly it integrates with Basecamp.

  • Overriding existing Rake tasks

    I added some long-running integration tests to a Rails application today and quickly began getting irritated that issuing the rake command runs all tests… unit, functional, AND integration. Since I run rake quite frequently, any sizable delay can quickly get annoying.

    The task that gets executed by rake is the :test task. After spending a few minutes trying to replace it, I discovered that there isn’t an immediately obvious way to override an existing task in Rake. After jumping through a few hoops, though, I did manage to do it.

    First, here’s my replacement for the existing :test task:

    task :test do
      Rake::Task["test:units"].invoke rescue got_error = true
      Rake::Task["test:functionals"].invoke rescue got_error = true
      raise "Test failures" if got_error
    end
    

    All it does is run the unit and functional tests, but no integration tests. I stuck this in my Rakefile right after the require 'tasks/rails' line. Next up, I reopened the Rake::TaskManager module to create my own little helper method to remove a task:

    Rake::TaskManager.class_eval do
      def remove_task(task_name)
        @tasks.delete(task_name.to_s)
      end
    end
    

    Lastly, I called this method from another method defined inside my Rakefile. This way, I could use syntax like remove_task :test which would fit with my other task definitions in the file. This is how everything looks put together (remember that this code should be inserted immediately after the require 'tasks/rails' line or it won’t work):

    Rake::TaskManager.class_eval do
      def remove_task(task_name)
        @tasks.delete(task_name.to_s)
      end
    end
    
    def remove_task(task_name)
      Rake.application.remove_task(task_name)
    end
    
    # Override existing test task to prevent integrations
    # from being run unless specifically asked for
    remove_task :test
    task :test do
      Rake::Task["test:units"].invoke rescue got_error = true
      Rake::Task["test:functionals"].invoke rescue got_error = true
      raise "Test failures" if got_error
    end
    

    This did the trick for me, but it’s kind of long. Anyone know a better way of doing it?

  • Andy Hunt crashes raleigh.rb tonight

    Andy Hunt will be speaking at the Raleigh-area Ruby Brigade meetup tonight. It’s sure to be a good show, so grab a fellow geek and head on down to Red Hat headquarters at 7 PM. Signs will direct you to the correct room. Also, if you want an even bigger helping of Ruby tonight, join us at 5:30 PM at Baja Burrito for our traditional round of pre-meeting chow and conversation.