Note: I published this post for the first time at the Codegram blog, so this is just a repost :)
A few days ago we started a new project at Codegram. The project (which is still in development) is a good challenge for us and a real motivator: we all were tired of using always the same technologies, so we decided to use some tools we hadn’t had opportunity to use. One of them is DataMapper.
So what is DataMapper and why using it?
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails’ ActiveRecord library.
So, as the Wikipedia article says, DataMapper is an alternative to ActiveRecord. So why using it instead of the default ActiveRecord?
- No need to write structural migrations
- Scoped relations
- Lazy loading on certain attribute types
- Strategic eager loading
- Default support for composite and natural keys
As you can see, DataMapper has some really interesting features. This post will be a little introduction to this ORM, let’s see some of them.
Using DataMapper with Rails 3.1
First of all, we have to add Datamapper to our Rails project. I haven’t found any metagem to include Rails and DataMapper basic gems, so we’ll have to use this in our Gemfile:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
You can also use the data_mapper
gem, which installs the most commonly used DataMapper gems. Visit its GitHub page for more info.
Our first DataMapper model
No more config needed! What now? Just start coding! Don’t forget to bundle install
first! Everything right? OK, then, here comes the important part: our first DataMapper model.
1 2 3 4 5 6 7 8 9 10 |
|
Wow! Amazing! Yeah! Looks beautiful, right? If we check the model line by line, we find that:
- The model no longer inherits from ActiveModel. Oh, wait, we are not using ActiveModel anymore, so looks legit.
- We include the Resource DataMapper module, which adds some basics methods and includes the Assertions module.
- We define the
id
attribute, which will be a Serial. You can find more info about DataMapper data types in the wiki. - We define three more attributes:
title
andsynopsis
(which areString
s) andedition
, which is anInteger
.
Now that we have our model written, we have to create the database before creating our first book. Once we enter rake -T
on our shell to see all our Rake tasks, we find two new tasks:
rake db:automigrate
will destroy all our data and update de database to the last versionrake db:autoupdate
will update our database without destroying our data
So what happens with rake db:migrate
? I don’t want to lose everything every time I migrate! Don’t worry, it’s aliased to rake db:autoupgrade
, so it won’t hurt you if you’re too used to rake db:migrate
.
We can now create our database with rake db:create db:autoupgrade
and we can create our first book in the database! Let’s open our beautiful Rails console and create our first book. <spam>
I’m using a real world example: a novel written by Patrick Rothfuss which all you fantasy-lovers should read. Oh, and people who just enjoy reading too :)</spam>
1 2 |
|
Wohoo! OMG it looks so beautiful! As I know you liked this way of defining the model’s attributes, let’s take a look at migrations before we go to the controller.
Structural migrations and lazy-loading
Structural migrations? I don’t know another way to call them, so I call them this way. Structural migrations are those that change a database table structure: the ones that add or remove a field, add or remove primary keys, change a field type or add or create a table. That is, all the migrations that define the current database structure. Those migrations don’t exist with DataMapper.
Let’s see the usual procedure with ActiveRecord (actually, the list order is not important):
- Think about the model’s attributes
- Add validations to the model
- Write a migration to create the model’s table and add attributes
So we often create the migration at the last moment to ensure we don’t forget any field. And I repeat, you won’t need this last step with DataMapper. Let’s take the example from above and suppose we want to modify some model attributes, so our Book model will now look like this:
1 2 3 4 5 6 7 8 9 10 11 |
|
Notice we’ve added two new attributes, author
and publication_year
, and we have changed synopsis
’s type from String
to Text
. Let’s update our database with rake db:migrate
and see what has changed:
1 2 3 4 |
|
So what has happened here? the database has been successfully updated to our last version: the book doesn’t have any edition number and now has an author and a publication year. And what about the synopsis? What does <not loaded>
mean? DataMapper lazy-loads some data types to make database queries faster. This means that fields with a lot of data (like Text
attributes) won’t be loaded until they are required, like in this example.
Other migrations
What if I really need a migration? Well, that’s a good point against DataMapper: this way of migrating and updating the database is really nice, but fails when we really need to change the data. There’s a gem out there called dm-migrations which could help you on that, but I haven’t tried it, so I can’t tell you anything about it right now. Sorry about that :(
Beautiful scoped associations
Let’s see another database-related feature from DataMapper: scoped associations. To see the point, we have to add two new models and modify our Book model a little bit:
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
Woah, not so fast! What does through: Resource
mean? Another beautiful DataMapper feature! Stablishing relations through Resource
makes DataMapper auto-create the table between books
and topics
, but that’s not all! You want beautiful things? You’ll have them. Open your rails console
and enter the following after migrating the database:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
WAIT AGAIN! What’s that?? Amazing, right? When defining a relation through Resource
, DataMapper creates a class so that relation becomes an object! Let’s try to destroy this one!
1 2 3 4 5 6 7 8 |
|
So you can play with relations modifying directly the relation object. Let’s keep with the scoped associations we were talking about before and try this on our rails console
again:
1 2 |
|
That’s how we get all the topics an author has written about without using dirty Arel Table relations, try this with ActiveRecord ;) Actually, associations are a really powerful resource with DataMapper. We could keep talking about them forever, but you can also take a look at the DataMapper associations docs page, which is pretty neat and clear about that. You can also take a look at the Finding docs page, where you’ll find another amazing feature with associations: queries combination.
Rails controllers with DataMapper
Just to end the post, I wanted to show you how a Rails controler looks with Datamapper. I’ve uploaded a gist with my BooksController so you can have a look at it:
As you see, it’s very similar to an ActiveRecord one, except for one thing: DataMapper doesn’t have a find
method. So use the get
method, which works pretty similar to the first one :)
Final thoughts
I must say I love the DataMapper approach about the model, this way of clearly showing what attributes a model has and the clean way DataMapper migrates the database. I’ve been looking for a good way to have my models information properly sorted and easy to access, and I think I can achieve it with DataMapper and some design pattern like Single Responsibility Principle. I just wanted to introduce you to DataMapper, an ORM not as used as ActiveRecord in Rails world, but I really think you should give it a try.
As a final note, you can find a debate on using DataMapper or ActiveRecord here. You’ll find some of the points explained in this post and some more to help you decide :)