DataMapperAn Introduction
Similarities
• Associations
• Validations
• Migrations
Identity Map
@parent = Parent.first(:name => 'John')
@parent.children.each do |child| child.parent.should == @parentend
# => true
Properties
class User include DataMapper::Resource property :name, String, :index => true, :nullable => false, :length => 30 property :email, String, :nullable => false, :length => 255, :format => :email_address property :password, String, :nullable => false property :remarks, Text
end
Custom Types
Custom Data-types
• Csv
• Enum
• EpochTime
• FilePath
• Flag
• IPAddress
• URI
• Yaml
• Regex
Lazy Loading
class Post .. property :body, Text, :lazy => false property :summary, Text, :lazy => [:show] property :subtitle, String, :lazy => [:show] property :views, Integer, :lazy => [:count] ..end
Multiple Repositories
class Page include DataMapper::Resource property :id, Serial property :name, String
repository(:legacy) do property :name, String, :field => 'title' endend
Page.all(:repository => :legacy)
Auto Validations
property :email, String, :length => 255, :nullable => false
# => email varchar(255) not null (create table SQL)# => validate_present :email# => validate_length :email, :max => 255
Migrations
• Auto Migrate
• Auto Upgrade
• Migration
Finding Records
exhibitions = Exhibition.all(:run_time.gt => 2, :run_time.lt => 5)
# => SQL conditions: 'run_time > 1 AND run_time < 5'
class Zoo # all the keys and property setup here def self.open all(:open => true) end
def self.big all(:animal_count.gte => 1000) endend
big_open_zoos = Zoo.big.open
big_open_zoos = Zoo.all(:open => true).all(:animal_count.gte => 1000)
big_open_zoos = Zoo.all(:open => true).all(:animal_count.gte => 1000)# => This line of code generate zero sql
big_open_zoos.each do |zoo| puts zoo.nameend# => This generates one sql.
• #each
• #first
• #last
• #count
• #map
• etc
Kicker methods
Strategic Eager Loading
Query Path
Person.all("addresses.street.like" => '%marina%')
SELECT "people"."id", "people"."name" FROM "people" INNER JOIN "addresses" ON ("people"."id" = "addresses"."person_id")WHERE ("addresses"."street" LIKE '%marina%')ORDER BY "people"."id"
Questions?