Rails with Datamapper

With the recent announcement that Rails and MERB will merge and my preference for DataMapper I decided to plug datamapper into rails for my next freelance project. The theory goes this should make the upgrade path to Rails 3 a lot simpler!

It's currently possible to use Datamapper with Rails, heck even DHH himself commented so, but it's not quite easy as using ActiveRecord. After a quick Google I only ran into question of how to do it, no howto guide. So I set out to make mine own - it really was quite simple in the end:

sudo gem install addressable data_objects do_mysql # do_mysql can be changed for do_postgres or do_sqlite3 as appropriate
sudo gem install dm-core dm-more

In the dm-more github repos there's a folder called rails_datamapper which is a plugin for rails to add datamapper support. This doesn't install with the dm-more gem so it's a case of cloning the git repository and copy the folder to your rails project:

git clone git://github.com/sam/dm-more.git 
cp -R dm-more/rails_datamapper /vendor/plugins

Then edit your project environment.rb file and add the following lines:

# Load the required gems in the correct order 
config.gem "addressable", :lib => "addressable/uri" 
config.gem "data_objects" 
config.gem "do_mysql" 
config.gem "dm-core"  

# Make datamapper load first as some plugins have dependencies on it
config.plugins = [ :rails_datamapper, :all ]

# Remove ActiveRecord if you no longer need it
config.frameworks -= [ :active_record ]

The connection to the database will be made by the rails_datamapper plugin using your database.yml configuration file. You'll need to use a slightly different format for datamapper:

development: 
:repositories: 
:adapter: mysql 
:database: opnli_dev

Or alternately you can specify your own initializer and forgo the rails plugin:

hash = YAML.load(File.new(RAILS_ROOT + "/config/database.yml")) DataMapper.setup(:default, hash[RAILS_ENV])

The only real gotcha in using datamapper is some rails plugins assume you're using ActiveRecord. Hopefully this won't be the case in the future, but for now you'll need to get forking!