It’s possible to use ActiveRecord to handle or test persistence, outside a Rails project. You can generate models, migrate and write specs just by using the AR gem.
And why would you ever want to use AR outside Rails? In my case, I am writing a gem which needs to parse models to generate schema structures and want to write specs within the gem to test for persistence.
There are blogs and gems dedicated to address this topic like:
- http://journal.dedasys.com/2007/01/28/using-migrations-outside-of-rails
- https://github.com/thuss/standalone-migrations
- http://blog.aizatto.com/2007/05/21/activerecord-without-rails/
The steps are pretty simple:
1. Use ActiveRecord gem
gem.add_dependency "activerecord", "~> 3.2.0" #if using in a gem
gem "activerecord", "~> 3.2.0" #in Gemfile for all other cases
2. Write/Generate a Migration
The simplest migration looks like this:
class CreatePosts < ActiveRecord::Migration def self.up create_table :posts, :force => true do |t| t.timestamps end end def self.down drop_table :yetis end end
You can either hand-code this block (Textmate, for one, has a pretty good Ruby-on-Rails bundle to support this) or you code use a gem like standalone-migrations to generate the model.
3. Establish a database connection
SQLite serves well to create a database on the fly:
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: "db/testdb"
You can also create a database.yml and pass it as a parameter to establish_connection. A standard database.yml looks like:
adapter: mysql database: database username: user password: password host: localhost
To load the database.yml:
require 'yaml'
dbconfig = YAML::load(File.open('database.yml')) ActiveRecord::Base.establish_connection(dbconfig)
4. Migrate to database
Use ActiveRecord::Migrator to generate the actual table in your database. If your migrations are present in a folder like schema/migrations, then:
ActiveRecord::Migrator.migrate("../schema/migrations")
5. Write a Test
describe "Post" do it "checks if Post is really an ActiveRecord::Base class" do Post.superclass.name.should eq "ActiveRecord::Base" end end
This should return a success.
Leave a comment