分享 一个 datamapper 的入门例子

chenge · 2012年11月03日 · 最后由 Tony612 回复于 2013年05月08日 · 3483 次阅读

感觉 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

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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号