分享 一个 datamapper 的入门例子

chenge · November 03, 2012 · Last by Tony612 replied at May 08, 2013 · 3484 hits

感觉 dm 有一些优点,隔离数据库,方便单元测试。用的是 include 方式,避免了继承。

require 'dm-core'
require 'dm-migrations'

# Open the database test1.db
DataMapper.setup :default, "sqlite3://#{Dir.pwd}/test1.db" 

# Define the Person model
class Person
  include DataMapper::Resource

  property :firstname, String
  property :lastname, String
  property :email, String, :key => true
end

# Automatically create the tables if they don't exist
DataMapper.auto_migrate!

# Create a new record
p = Person.new
p.attributes = {
  :firstname => 'John',
  :lastname => 'Doe',
  :email => '[email protected]'
}

# Save it to the database
p.save

# Make some changes to the object
p.lastname = 'Smith'
p.save

# Create a new object and destroy it
p2 = Person.new
p2.email = '[email protected]'
p2.save

p2.destroy

# Find a record from the database
p3 = Person.get('[email protected]')
puts p3.inspect

origin:http://ruby.about.com/od/sinatra/a/datamapper.htm

话说有谁在真实项目里实践过这个么? 感觉怎么样啊?
刚刚偶然看到这个,就搜索进来了

You need to Sign in before reply, if you don't have an account, please Sign up first.