26
DataMapper An Introduction

Dm Intro

  • Upload
    tohchye

  • View
    888

  • Download
    2

Embed Size (px)

DESCRIPTION

An introduction to DataMapper

Citation preview

Page 1: Dm Intro

DataMapperAn Introduction

Page 2: Dm Intro

Similarities

• Associations

• Validations

• Migrations

Page 3: Dm Intro

Identity Map

Page 4: Dm Intro

@parent = Parent.first(:name => 'John')

@parent.children.each do |child| child.parent.should == @parentend

# => true

Page 5: Dm Intro

Properties

Page 6: Dm Intro

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

Page 7: Dm Intro

Custom Types

Page 8: Dm Intro

Custom Data-types

• Csv

• Enum

• EpochTime

• FilePath

• Flag

• IPAddress

• URI

• Yaml

• Regex

Page 9: Dm Intro

Lazy Loading

Page 10: Dm Intro

class Post .. property :body, Text, :lazy => false property :summary, Text, :lazy => [:show] property :subtitle, String, :lazy => [:show] property :views, Integer, :lazy => [:count] ..end

Page 11: Dm Intro

Multiple Repositories

Page 12: Dm Intro

class Page include DataMapper::Resource property :id, Serial property :name, String

repository(:legacy) do property :name, String, :field => 'title' endend

Page.all(:repository => :legacy)

Page 13: Dm Intro

Auto Validations

Page 14: Dm Intro

property :email, String, :length => 255, :nullable => false

# => email varchar(255) not null (create table SQL)# => validate_present :email# => validate_length :email, :max => 255

Page 15: Dm Intro

Migrations

Page 16: Dm Intro

• Auto Migrate

• Auto Upgrade

• Migration

Page 17: Dm Intro

Finding Records

Page 18: Dm Intro

exhibitions = Exhibition.all(:run_time.gt => 2, :run_time.lt => 5)

# => SQL conditions: 'run_time > 1 AND run_time < 5'

Page 19: Dm Intro

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

Page 20: Dm Intro

big_open_zoos = Zoo.all(:open => true).all(:animal_count.gte => 1000)

Page 21: Dm Intro

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.

Page 22: Dm Intro

• #each

• #first

• #last

• #count

• #map

• etc

Kicker methods

Page 23: Dm Intro

Strategic Eager Loading

Page 24: Dm Intro

Query Path

Page 25: Dm Intro

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"

Page 26: Dm Intro

Questions?