Managing database.yml with Capistrano 2.0

Posted by shane
on Wednesday, May 30

Jeremy Voorhis posted a really great Capistrano recipe for managing database.yml which dynamically creates a database.yml file in your shared directory on setup, and symlinks your app’s database.yml once it’s deployed. This is great if you don’t version control your database.yml file for security reasons or working with multiple developers.

changes the syntax for task callbacks and gets rid of the useful render method.  However, using ERb, Ruby's built-in templating system, isn't much more difficult than using the old render method.  Here is Jeremy's script updated for Capistrano 2.0 using ERb and the new namespaced callback syntax.
require 'erb'

before "deploy:setup", :db
after "deploy:update_code", "db:symlink" 

namespace :db do
  desc "Create database yaml in shared path" 
  task :default do
    db_config = ERB.new <<-EOF
    base: &base
      adapter: mysql
      socket: /tmp/mysql.sock
      username: #{user}
      password: #{password}

    development:
      database: #{application}_dev
      <<: *base

    test:
      database: #{application}_test
      <<: *base

    production:
      database: #{application}_prod
      <<: *base
    EOF

    run "mkdir -p #{shared_path}/config" 
    put db_config.result, "#{shared_path}/config/database.yml" 
  end

  desc "Make symlink for database yaml" 
  task :symlink do
    run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml" 
  end
end

Until I get better syntax highlighting for this blog, check out the Pastie for the color version. For more info on whats new in Capistrano 2.0, check out Jamis’ preview and Geoff’s post. Also, props to Jamis for suggesting I use ERb directly.

Update: Updated code to use its own :db namespace instead of the default one. The database yaml file will be created by the default :db task, and the symlink will be created by the db:symlink task. Note how namespaces in Cap 2.0 allows us to have two symlink tasks, one in the deploy namespace and the other in db.

RailsConf 2007 Notes

Posted by shane
on Tuesday, May 29

All my notes from the RailsConf sessions are here. They don’t contain everything from the sessions I attended, just mostly things that were either new to me or were of some importance. O’Reilly put up most of the presentation slides on their site. Does anyone have notes on Uncle Bob’s Clean Code presentation? The one on the O’Reilly site is Java-specific. He didn’t do a Java talk at RailsConf did he?

If anyone was at Dante’s on Saturday night, and took pictures of the Exta Action Marching Band, I’d love to see them.

Giving You More Free Time

Posted by shane
on Tuesday, May 29

(and previously Hobo and the Sexy Migrations plugin) gave us automatic created\_at and updated\_at fields in our migrations, using the timestamps keyword.

How about bringing some of this sexiness to generators and taking it a step further? Well my patch was accepted and Rails now automatically adds timestamps to all generated migrations. So when you generate a model, scaffold, or resource, you will get timestamps for free. It is the equivalent of adding created\_at:datetime and updated\_at:datetime to your generators. So

script/generate model post title:string
will do the same thing as
script/generate model post title:string created\_at:datetime updated\_at:datetime

This is nothing significant but I hope it saves people a few keystrokes. If you don’t need timestamps you can always just delete the associated lines from your migration file and the fixtures. Just another example of Rails making it easier to do common things. This is currently only available in Edge Rails.

assert_difference Exposed

Posted by shane
on Wednesday, May 23

assert_difference is my favorite Rails test helper, and until a few weeks ago, was sitting in a helper class that I used to add to all my projects. It is now in Rails core. There were a few versions of it floating around, so it is good that we now have only one version to deal with.

What can you do with it?

One of the most common idioms I’ve run into in testing, is to count the number of records associated with a Model, create a new one, and make sure the count incremented by one. In the old days, we had to do this:

def test_should_create_user
  num_users = User.count
  user = create_user
  assert !user.new_record?, "#{user.errors.full_messages.to_sentence}" 
  assert_equal num_users + 1, User.count
end

Now we can do:

def test_should_create_user
  assert_difference 'User.count' do
    user = create_user
    assert !user.new_record?, "#{user.errors.full_messages.to_sentence}" 
  end
end

We saved one line, and got rid of repeating User.count. assert\_difference gets very close to my limit of too much magic, but I still like how it cleans up tests, especially if you use it with assert\_no\_difference as well. You aren’t forced to use it, just like you aren’t forced to scaffold.

How does it work?

Here is what the source looks like:

 # File vendor/rails/activesupport/lib/active_support/core_ext/test/difference.rb
22:       def assert_difference(expression, difference = 1, &block)
23:         expression_evaluation = lambda { eval(expression, block.binding) }
24:         original_value        = expression_evaluation.call
25:         yield
26:         assert_equal original_value + difference, expression_evaluation.call
27:       end

We pass in our expression 'User.count', the default difference of 1, and the block to assert_difference. We then evaluate the expression User.count and store it in a Proc object, since lambda converts a block to a Proc object. A Proc object allows us to store a chunk of code and evaluate it at a later time, while maintaining the context of its original definition. If we currently have 3 users, original\_value will have a value of 3 in line 24. Then we yield to the block and create the new user. Finally we will add 1 to the original\_value of 3 and re-evaluate the expression User.count by calling the Proc object. Since the new user was created, the User count is now 4 and the test will pass. Notice how eval is passed in the binding of the block. This causes the evaluated expression to run in the context of the block. I don’t think this makes a difference in this specific example, but it makes sense, since User.count is more associated with the block than the top-level binding of the test method.

Why are you telling me all this?

Of course you don’t need to know all of this to use assert_difference. I just thought it was a well written method that demonstrates practical use of Proc objects.

Update:

If you are using acts\_as\_authenticated or restful\_authentication, you will have to go in and change your model unit test to use assert\_difference 'Model.count' do instead of assert\_difference Model, :count do. If you are working on a new project and going to use aaa, use this patch to fix your tests.

Finally Made the Plunge

Posted by shane
on Monday, May 07

I did it. I’m no longer a full-time Java developer. At nearly 2.5 years of doing Rails part-time, I’m practically an old-timer. Many of you who started learning Ruby and Rails around the time I did have had much success doing freelance work. I’m happy to announce the creation of CrimsonJet, LLC., which will provide Agile, test-driven Rails development solutions.

I also hope to introduce a few web apps that I have been working on for the past few months and step up my open-source contributions. Check out my RailsConf plan and definitely get in touch with me if you want to meet up in Portland.

More real content coming soon. Watch this space! :)

Side note: I am not anti-Java or pro-Ruby (okay fine, maybe a little). I believe in using the right tool or mix of tools for the job. For far too long people have been using sledge-hammers to drive in push-pins.