Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

272 | Chapter 9: Incorporating and Extending Rails


DataMapper


The DataMapper library (http://www.datamapper.org/) is based on Martin Fowler’s
Data Mapper pattern, which is similar to Active Record but with less coupling.
Active Record’s chief structural weakness is that it ties the database schema to the
object model. We see this happen in Rails when using ActiveRecord. Every struc-
tural change we want to make to the objects must be reflected in the database at the
same time.


The Data Mapper pattern provides a better balance when the object model and data-
base need to evolve separately. The drawback is that there will be some duplication.
Because of the additional layer of indirection, DataMapper cannot infer your object’s
structure from the database like ActiveRecord can. This is the necessary price of
flexibility.


DataMapper confers several other advantages over ActiveRecord:



  • DataMapper includes an implementation of the Identity Map pattern, which
    ensures that each database record is loaded only once. ActiveRecord will hap-
    pily allow a record to be loaded many times, which can potentially cause con-
    flicts when one becomes stale.

  • Empirically, DataMapper is faster than ActiveRecord. The code is also smaller
    and less complicated. This can be good or bad, depending on whether you need
    ActiveRecord’s more advanced features.

  • DataMapper can generate your database tables from their Ruby description:
    class Person < DataMapper::Base

    (property definitions)


    end




# Create the table based on the above properties
database.save(Person)

DataMapper defines a top-level method,database, that returns the
current database session. As a top-level method (defined onObject), it
can be used anywhere. DataMapper plays nicely, though—the method
will not be defined if there is already another top-level method with
the same name.

It does not have ActiveRecord’s complex migration support, which means that
any production schema changes must be done manually. But it does have a con-
venient task to recreate the entire schema, destroying any data in the process:
DataMapper::Base.auto_migrate!

DataMapper is very easy to use with Rails. It detects when it is being run under Rails
and reads theconfig/database.ymlfile for a connection specification. So, everything
should be ready to go with agem install datamapper and one line in a Rails initializer:


require 'data_mapper'
Free download pdf