Categories
General

How To Disable an Observer in Rails

I wanted to disable an ActiveRecord::Observer during a migration in my Rails application. For the record, simply:

Payment.delete_observers

Update: October 17, 2009

The previous code is problematic, it will disable the PaymentObserver for the entire test run.

I’ve now switched to the following technique:

class OrderTest < ActiveSupport::TestCase
  include FlexMock::TestCase
  context "with observers disabled" do
    setup do
      # Disable order updates made by PaymentObserver
      flexmock(PaymentObserver.instance, :after_create => true)
    end
    context "...more tests..." do
    end
  end
end

You can adapt to whatever mocking framework you’re using. You simply mock any methods in your observer class that you don’t want called.

Categories
General

Rich Frog: Git with Putty on Windows

When searching for information how to use use PuTTY with git on Windows, I came across this post: Rich Frog: Git with Putty on Windows. The first time I tried to connect to unfuddle.com, I wasn’t able to add the server’s host key to the cache. Hitting the ‘y’ key did nothing. In order to fix this, I connected manually to the host using plink with the following command:

plink git@subdomain.unfuddle.com

Then added the server’s host key to the cache. After which, connecting using git worked as expected.

Categories
General

How To: Add current commit to Rails template

I wanted to add the current revision of a Rails project to my layout so I can easily know what version the current code base is running. I came up with a short initializer that can be added to define a global constant for the commit id and commit timestamp.

# RAILS_ROOT/config/initializers/tag_revision.rb
# Call +git+ and obtain the current commit SHA1 and commit date. Store these values
# in +PROJECT_VERSION_COMMIT_ID+ and +PROJECT_VERSION_COMMIT_DATE+. Then define
# +PROJECT_VERSION+ to be a string of the two.
git_cmd = 'git show --pretty=format:"%H|%ci" --quiet'
commit_id = nil
commit_date = nil
begin
  commit_id, commit_date = IO.popen(git_cmd) {|f| f.gets.split("|") }
rescue Errno::ENOENT # git not available
  commit_id = 'Unknown'
  commit_date = ''
end
unless defined?(::PROJECT_VERSION)
  ::PROJECT_VERSION_COMMIT_ID = commit_id
  ::PROJECT_VERSION_COMMIT_DATE = commit_date
  ::PROJECT_VERSION = "#{commit_id} #{commit_date}"
end
# app/helpers/application_helper.rb
module ApplicationHelper
  def link_to_version
    if ENV['RAILS_ENV'] == 'development'
      link_to PROJECT_VERSION, "http://subdomain.unfuddle.com/repositories/commit/#{PROJECT_COMMIT_ID}"
    else
      PROJECT_VERSION
    end
  end
end
# app/views/layout/application.html
....
<div id="footer"> <%= link_to_version %> </div>

When the application is run in development mode, a link will appear in the footer to the hosted repository. I’m using Unfuddle for my project but you can obviously return anything you want in the helper.