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

(Tuis.) #1
Replacing Rails Components | 273

DataMapper uses many of the same constructs as Rails. Start out by defining a model
class that inherits fromDataMapper::Base:


class Person < DataMapper::Base
# ...
end

Within the class definition,propertymethods define fields that should be mapped
from the class to the relational database:


class Person < DataMapper::Base
property :first_name, :string
property :last_name, :string
property :biography, :text

# Associations work pretty much like ActiveRecord...
# belongs_to :company, :foreign_key => 'firm_id'
# has_many :transactions, :class => FinancialTransaction
end

DataMapper comes with a set of convenience methods that behave like ActiveRecord
object lifecycle methods. For example, the syntax to create aPersonis the same as
under ActiveRecord:


>> p = Person.new :first_name => 'John', :last_name => 'Smith',
:biography => 'Something about John'
=> #<Person:0x13ce99c @new_record=true, @first_name="John",
@last_name="Smith", @biography="Something about John", @id=nil>
>> p.save
=> 1
>> p
=> #<Person:0x13ce99c @new_record=false, @first_name="John",
@last_name="Smith", @biography="Something about John", @id=1>

Notice that under DataMapper, the attributes ofPersonare directly
stored as instance variables of thePersonobject. In ActiveRecord,
these attributes would be stored in a hash as the@attributesvariable.
In some ways, DataMapper’s approach is cleaner, as it avoids another
layer of indirection.

There are many more features behind DataMapper, and the full set of documenta-
tion can be found athttp://www.datamapper.org/. API documentation is also avail-
able athttp://datamapper.rubyforge.org/.


Ambition


Chris Wanstrath’s Ambition project (http://errtheblog.com/post/10722) is an amaz-
ing little experiment that turns Ruby code into SQL almost transparently. Using
Ryan Davis’s ParseTree library, Ambition walks the Ruby abstract syntax tree and
turns various methods into their corresponding SQL queries.

Free download pdf