ActiveRecord, quickly

Thursday, September 06

I often want to experiment with a database model using ActiveRecord, from outside the context of a Rails application. Ideally, I want to do this all in one file. Where I can see my migrations and my models at the same time and tweak as needed.

This is the stub I’ve been using lately for that task.

require 'rubygems'
require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDOUT) if 'irb' == $0

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql',
  :database => 'example',
  :username => 'root',
  :host     => 'localhost'
)

ActiveRecord::Base.silence do
  ActiveRecord::Schema.define(:version => 1) do
    with_options :force => true do |m|
      m.create_table 'examples' do |t|
        t.string :title
        t.timestamps
      end
    end
  end
end

class Example < ActiveRecord::Base
end

if __FILE__ == $0
  require 'test/unit'

  class TestExample < Test::Unit::TestCase
    def test_should_flunk
      flunk
    end
  end
end

I simply define all my migrations and each model class here, and then write a few tests to ensure things are working the way I expect. Changing the schema and adding/removing fields is a snap, and the database tables are dropped and recreated each time the file is run.

The tests are run selectively, and AR::Logger is set to STDOUT when $0 is irb because I often want to play with my creation interactively on the console. This helps me get a sense of how things work, and how my objects feel from an API perspective.

Here’s what the stub above looks like from an irb session:

$ irb
>> require 'example_models'
-- create_table("examples", {:force=>true})
   -> 0.1467s
-- initialize_schema_information()
   -> 0.0006s
-- columns("schema_info")
   -> 0.0027s
=> true

>> Example.create!
  Example Columns (0.064651)   SHOW FIELDS FROM examples
  SQL (0.000134)   BEGIN
  SQL (0.000316)   INSERT INTO examples (`updated_at`, `title`, `created_at`) VALUES('2007-09-06 11:14:05', NULL, '2007-09-06 11:14:05')
  SQL (0.000682)   COMMIT
=> #<Example id: 1, title: nil, created_at: "2007-09-06 11:14:05", updated_at: "2007-09-06 11:14:05">
>> 

I find this to be a really fast way to prototype ideas.

Comments

Leave a response