SlideShare una empresa de Scribd logo
1 de 32
Descargar para leer sin conexión
Replacing ActiveRecord
   with DataMapper
    in Ruby on Rails



         Peter Degen-Portnoy
         November 25, 2008
DataMapper is an ORM
A lot like ActiveRecord
●
    DB Adapters
●
    Migrations
●
    Associations
    ●
        One to one
    ●
        One to many
    ●
        Many to many
    ●
        Many to one
Application       Rails                Merb




ORM                       DataMapper




Adaptors      DO.rb         YAML          IMAP




Storage
Most often used with Merb

               ...but not exclusively
DataMapper Goodness
●
    Identity Map
●
    Mappings in Model
●
    Multiple Repositories
●
    Lazy Loads of Large Lumps
●
    Strategic Eager Loading
Identity Map
●
    One object for one row
●
    Reduces hits to database
●
    Exists during Identity Map Session
Mapping in Model
●
    Persist any class
●
    Independent data store evolution
●
    Connect to multiple databases
●
    DM issues updates or creates only for what
    it knows
Multiple Repositories
●
    Nested YAML structure
●
    Override target table names
●
    Specify connection per class or even call
Lazy Loading
●
    Reduces load of large columns
    ●
        Text
    ●
        Blobs
    ●
        Graphics
●
    Specify which columns lazy load
●
    Lazy loads happen together; only 1 more call
●
    Can be grouped
Strategic Eager Loading
●
    One call per child
●
    Eliminates n+1 calls for associations
Way faster than ActiveRecord
10,000 records fetched w/ Active Record
        Average: 1.3429 seconds
10,000 records fetched w/ DataMapper
       Average: 0.0002 seconds
1.3429 seconds compared to 0.0002 seconds
0.0150% as much time
To Fetch 1,000 Records

ActiveRecord           Over 204,000 calls

DataMapper             Under 7,000 calls
Replacing ActiveRecord with DataMapper

            the part for which you have been waiting
Demo Applications
●
    One application to test ActiveRecord
●
    One application to test DataMapper
●
    Each create same data structure:
    ●
        script/generate model book amount:float
        date:date name:string description:text
        --skip-timestamps
●
    Create 1000 records
    ●
        Profile & Benchmark
Gems You Need
●
    data_mapper
●
    do_mysql (or do_postgres or do_sqlite3)
●
    dm-core
●
    fastthread
●
    json
●
    rspec
Edit config/environment.rb
●
    config.frameworks -= [ :active_record ]
●
    config.gem “do_mysql”
●
    config.gem “dm-core”
●
    config.gem “dm-migrations”


    Make sure your gems are up to date by
    running “sudo rake gems:install”
Configure database.yml
development: &defaults
 :adapter: mysql
 :database: dm2_dev
 :user: root
 :password: mysql
 :socket: /var/run/mysqld/mysqld.sock
 :host: localhost

test:
 <<: *default
 :database: dm2_test

production:
 <<: *default
 :database: dm2_prod
Create
 config/initializers/datamapper.rb
require quot;dm-corequot;
hash = YAML.load(File.new(Rails.root + quot;/config/database.ymlquot;))
DataMapper.setup(:default, 'mysql://root:mysql@localhost/dm2_dev' )
Generate Model
> script/generate dm_model book amount:float date:date name:string
description:text --skip-migration



NOTE: --skip-migration is needed because the rails-datamapper integration
gem doesn't pull out the ActiveRecord dependency on migration creation
yet.
Finish model definition
require 'lorem'

class Book
 include DataMapper::Resource
 property :id, Integer, :serial => true
 property :amount, Float
 property :date, Date
 property :name, String
 property :description, Text, :lazy => true

 def self.create_dummy_data(num)
  num.times do |number|
   t = Book.new
   t.attributes = {:amount => number, :date => Time.now(),
         :name => Lorem.lorem(4, false), :description => Lorem.lorem(60, false)}
   t.save
  end
 end
end
Create Migration
migration 1, :create_books do
 up do
   create_table :books do
    column :id, Integer, :serial => true, :nullable? => false, :key => true
    column :amount, Float
    column :date, Date
    column :name, String
    column :description, DataMapper::Types::Text
   end
 end

 down do
  drop_table :books
 end
end
Create Migration Rake Task
namespace :dm do
  task :migrate => :environment do
   gem quot;dm-migrationsquot;
   require quot;migration_runnerquot;
   Dir[File.join(Rails.root, quot;dbquot;, quot;migratequot;, quot;*quot;)].each {|f| require f}
   migrate_up!
  end
 end



src/dm2> mysqladmin create dm2_dev
src/dm2> rake dm:migrate
Wire up application
●
    Create Controller for book
●
    Create “bulk” generation capability
Summary Checklist
●
    Add gems & generate application
●
    Remove ActiveRecord & add DataMapper
●
    Configure database.yml & datamapper.rb
●
    Create your database
●
    Generate your model, complete definition &
    migrate
●
    Continue defining application
Additional Goodness
●
    Validations
●
    Conditions
●
    Order
●
    Aggregations
●
    Associations
●
    Named Scope (class methods)
Assessment
●
    Can't beat the speed
●
    Outstanding flexibility
●
    Durn if it won't be more complex to develop
    with
Thank you

Más contenido relacionado

La actualidad más candente

Introduction to AWS Big Data
Introduction to AWS Big Data Introduction to AWS Big Data
Introduction to AWS Big Data Omid Vahdaty
 
Amazon RedShift - Ianni Vamvadelis
Amazon RedShift - Ianni VamvadelisAmazon RedShift - Ianni Vamvadelis
Amazon RedShift - Ianni Vamvadelishuguk
 
Hadoop and Cassandra at Rackspace
Hadoop and Cassandra at RackspaceHadoop and Cassandra at Rackspace
Hadoop and Cassandra at RackspaceStu Hood
 
Dynamo db pros and cons
Dynamo db  pros and consDynamo db  pros and cons
Dynamo db pros and consSaniya Khalsa
 
Scalable PHP Applications With Cassandra
Scalable PHP Applications With CassandraScalable PHP Applications With Cassandra
Scalable PHP Applications With CassandraAndrea De Pirro
 
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...Amazon Web Services
 
SORT & JOIN IN SPARK 2.0
SORT & JOIN IN SPARK 2.0SORT & JOIN IN SPARK 2.0
SORT & JOIN IN SPARK 2.0Sigmoid
 
Using Cassandra with your Web Application
Using Cassandra with your Web ApplicationUsing Cassandra with your Web Application
Using Cassandra with your Web Applicationsupertom
 
Partners in Crime: Cassandra Analytics and ETL with Hadoop
Partners in Crime: Cassandra Analytics and ETL with HadoopPartners in Crime: Cassandra Analytics and ETL with Hadoop
Partners in Crime: Cassandra Analytics and ETL with HadoopStu Hood
 
ScyllaDB's Avi Kivity on UDF, UDA, and the Future
ScyllaDB's Avi Kivity on UDF, UDA, and the FutureScyllaDB's Avi Kivity on UDF, UDA, and the Future
ScyllaDB's Avi Kivity on UDF, UDA, and the FutureScyllaDB
 
Scaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSScaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSMax Neunhöffer
 
Dynamo DB & RDS Deep Dive - AWS India Summit 2012
Dynamo DB & RDS Deep Dive - AWS India Summit 2012Dynamo DB & RDS Deep Dive - AWS India Summit 2012
Dynamo DB & RDS Deep Dive - AWS India Summit 2012Amazon Web Services
 
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBase
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBaseHBaseCon2017 Efficient and portable data processing with Apache Beam and HBase
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBaseHBaseCon
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKSkills Matter
 
HBaseCon 2015- HBase @ Flipboard
HBaseCon 2015- HBase @ FlipboardHBaseCon 2015- HBase @ Flipboard
HBaseCon 2015- HBase @ FlipboardMatthew Blair
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For HadoopCloudera, Inc.
 
How to scale your web app
How to scale your web appHow to scale your web app
How to scale your web appGeorgio_1999
 
What Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database ScalabilityWhat Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database Scalabilityjbellis
 

La actualidad más candente (20)

Introduction to AWS Big Data
Introduction to AWS Big Data Introduction to AWS Big Data
Introduction to AWS Big Data
 
Amazon RedShift - Ianni Vamvadelis
Amazon RedShift - Ianni VamvadelisAmazon RedShift - Ianni Vamvadelis
Amazon RedShift - Ianni Vamvadelis
 
Hadoop and Cassandra at Rackspace
Hadoop and Cassandra at RackspaceHadoop and Cassandra at Rackspace
Hadoop and Cassandra at Rackspace
 
Dynamo db pros and cons
Dynamo db  pros and consDynamo db  pros and cons
Dynamo db pros and cons
 
Scalable PHP Applications With Cassandra
Scalable PHP Applications With CassandraScalable PHP Applications With Cassandra
Scalable PHP Applications With Cassandra
 
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...
Consolidate MySQL Shards Into Amazon Aurora Using AWS Database Migration Serv...
 
SORT & JOIN IN SPARK 2.0
SORT & JOIN IN SPARK 2.0SORT & JOIN IN SPARK 2.0
SORT & JOIN IN SPARK 2.0
 
Using Cassandra with your Web Application
Using Cassandra with your Web ApplicationUsing Cassandra with your Web Application
Using Cassandra with your Web Application
 
Partners in Crime: Cassandra Analytics and ETL with Hadoop
Partners in Crime: Cassandra Analytics and ETL with HadoopPartners in Crime: Cassandra Analytics and ETL with Hadoop
Partners in Crime: Cassandra Analytics and ETL with Hadoop
 
No SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability MeetupNo SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability Meetup
 
ScyllaDB's Avi Kivity on UDF, UDA, and the Future
ScyllaDB's Avi Kivity on UDF, UDA, and the FutureScyllaDB's Avi Kivity on UDF, UDA, and the Future
ScyllaDB's Avi Kivity on UDF, UDA, and the Future
 
Cloud Optimized Big Data
Cloud Optimized Big DataCloud Optimized Big Data
Cloud Optimized Big Data
 
Scaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSScaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOS
 
Dynamo DB & RDS Deep Dive - AWS India Summit 2012
Dynamo DB & RDS Deep Dive - AWS India Summit 2012Dynamo DB & RDS Deep Dive - AWS India Summit 2012
Dynamo DB & RDS Deep Dive - AWS India Summit 2012
 
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBase
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBaseHBaseCon2017 Efficient and portable data processing with Apache Beam and HBase
HBaseCon2017 Efficient and portable data processing with Apache Beam and HBase
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
 
HBaseCon 2015- HBase @ Flipboard
HBaseCon 2015- HBase @ FlipboardHBaseCon 2015- HBase @ Flipboard
HBaseCon 2015- HBase @ Flipboard
 
Hw09 Sqoop Database Import For Hadoop
Hw09   Sqoop Database Import For HadoopHw09   Sqoop Database Import For Hadoop
Hw09 Sqoop Database Import For Hadoop
 
How to scale your web app
How to scale your web appHow to scale your web app
How to scale your web app
 
What Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database ScalabilityWhat Every Developer Should Know About Database Scalability
What Every Developer Should Know About Database Scalability
 

Destacado

CMST 225 Final Slidecast
CMST 225 Final SlidecastCMST 225 Final Slidecast
CMST 225 Final Slidecastmaxdevine1
 
Twin Cities SlideShare
Twin Cities SlideShareTwin Cities SlideShare
Twin Cities SlideSharemaxdevine1
 
The Near Future of CSS
The Near Future of CSSThe Near Future of CSS
The Near Future of CSSRachel Andrew
 
Classroom Management Tips for Kids and Adolescents
Classroom Management Tips for Kids and AdolescentsClassroom Management Tips for Kids and Adolescents
Classroom Management Tips for Kids and AdolescentsShelly Sanchez Terrell
 
The Presentation Come-Back Kid
The Presentation Come-Back KidThe Presentation Come-Back Kid
The Presentation Come-Back KidEthos3
 
The Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris LemaThe Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris LemaChris Lema
 

Destacado (7)

Slideshare
SlideshareSlideshare
Slideshare
 
CMST 225 Final Slidecast
CMST 225 Final SlidecastCMST 225 Final Slidecast
CMST 225 Final Slidecast
 
Twin Cities SlideShare
Twin Cities SlideShareTwin Cities SlideShare
Twin Cities SlideShare
 
The Near Future of CSS
The Near Future of CSSThe Near Future of CSS
The Near Future of CSS
 
Classroom Management Tips for Kids and Adolescents
Classroom Management Tips for Kids and AdolescentsClassroom Management Tips for Kids and Adolescents
Classroom Management Tips for Kids and Adolescents
 
The Presentation Come-Back Kid
The Presentation Come-Back KidThe Presentation Come-Back Kid
The Presentation Come-Back Kid
 
The Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris LemaThe Buyer's Journey - by Chris Lema
The Buyer's Journey - by Chris Lema
 

Similar a Replacing ActiveRecord With DataMapper

When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Railsdosire
 
Understanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLUnderstanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLHyderabad Scalability Meetup
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteDr Nic Williams
 
Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming Djamel Zouaoui
 
SnappyData overview NikeTechTalk 11/19/15
SnappyData overview NikeTechTalk 11/19/15SnappyData overview NikeTechTalk 11/19/15
SnappyData overview NikeTechTalk 11/19/15SnappyData
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About RailsAdam Wiggins
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management Systempsathishcs
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On RailsSteve Keener
 
Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Lucas Jellema
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHPRob Knight
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageSATOSHI TAGOMORI
 
Speed up R with parallel programming in the Cloud
Speed up R with parallel programming in the CloudSpeed up R with parallel programming in the Cloud
Speed up R with parallel programming in the CloudRevolution Analytics
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 

Similar a Replacing ActiveRecord With DataMapper (20)

When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
 
Spark streaming
Spark streamingSpark streaming
Spark streaming
 
Understanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLUnderstanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQL
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
CouchDB
CouchDBCouchDB
CouchDB
 
Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming
 
SnappyData overview NikeTechTalk 11/19/15
SnappyData overview NikeTechTalk 11/19/15SnappyData overview NikeTechTalk 11/19/15
SnappyData overview NikeTechTalk 11/19/15
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
 
DataMapper
DataMapperDataMapper
DataMapper
 
Nike tech talk.2
Nike tech talk.2Nike tech talk.2
Nike tech talk.2
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management System
 
Dancing with the Elephant
Dancing with the ElephantDancing with the Elephant
Dancing with the Elephant
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On Rails
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)Java Developers, make the database work for you (NLJUG JFall 2010)
Java Developers, make the database work for you (NLJUG JFall 2010)
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Taming NoSQL with Spring Data
Taming NoSQL with Spring DataTaming NoSQL with Spring Data
Taming NoSQL with Spring Data
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby Usage
 
Speed up R with parallel programming in the Cloud
Speed up R with parallel programming in the CloudSpeed up R with parallel programming in the Cloud
Speed up R with parallel programming in the Cloud
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 

Último

English basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfEnglish basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfbromerom1
 
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls AgencyCall Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls Agencykojalkojal131
 
Benefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBenefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBrantfordIndia
 
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Mikko Kangassalo
 
integrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfintegrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfAmitRout25
 
ingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesJessicaEscao
 
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...JeylaisaManabat1
 
The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)Shakti Savarn
 
Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi OneDay18
 

Último (9)

English basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfEnglish basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdf
 
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls AgencyCall Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
 
Benefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBenefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in India
 
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
 
integrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfintegrity in personal relationship (1).pdf
integrity in personal relationship (1).pdf
 
ingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet sauces
 
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
 
The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)
 
Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi
 

Replacing ActiveRecord With DataMapper

  • 1. Replacing ActiveRecord with DataMapper in Ruby on Rails Peter Degen-Portnoy November 25, 2008
  • 3. A lot like ActiveRecord ● DB Adapters ● Migrations ● Associations ● One to one ● One to many ● Many to many ● Many to one
  • 4. Application Rails Merb ORM DataMapper Adaptors DO.rb YAML IMAP Storage
  • 5. Most often used with Merb ...but not exclusively
  • 6. DataMapper Goodness ● Identity Map ● Mappings in Model ● Multiple Repositories ● Lazy Loads of Large Lumps ● Strategic Eager Loading
  • 7. Identity Map ● One object for one row ● Reduces hits to database ● Exists during Identity Map Session
  • 8. Mapping in Model ● Persist any class ● Independent data store evolution ● Connect to multiple databases ● DM issues updates or creates only for what it knows
  • 9. Multiple Repositories ● Nested YAML structure ● Override target table names ● Specify connection per class or even call
  • 10. Lazy Loading ● Reduces load of large columns ● Text ● Blobs ● Graphics ● Specify which columns lazy load ● Lazy loads happen together; only 1 more call ● Can be grouped
  • 11. Strategic Eager Loading ● One call per child ● Eliminates n+1 calls for associations
  • 12. Way faster than ActiveRecord
  • 13. 10,000 records fetched w/ Active Record Average: 1.3429 seconds
  • 14. 10,000 records fetched w/ DataMapper Average: 0.0002 seconds
  • 15. 1.3429 seconds compared to 0.0002 seconds
  • 17. To Fetch 1,000 Records ActiveRecord Over 204,000 calls DataMapper Under 7,000 calls
  • 18. Replacing ActiveRecord with DataMapper the part for which you have been waiting
  • 19. Demo Applications ● One application to test ActiveRecord ● One application to test DataMapper ● Each create same data structure: ● script/generate model book amount:float date:date name:string description:text --skip-timestamps ● Create 1000 records ● Profile & Benchmark
  • 20. Gems You Need ● data_mapper ● do_mysql (or do_postgres or do_sqlite3) ● dm-core ● fastthread ● json ● rspec
  • 21. Edit config/environment.rb ● config.frameworks -= [ :active_record ] ● config.gem “do_mysql” ● config.gem “dm-core” ● config.gem “dm-migrations” Make sure your gems are up to date by running “sudo rake gems:install”
  • 22. Configure database.yml development: &defaults :adapter: mysql :database: dm2_dev :user: root :password: mysql :socket: /var/run/mysqld/mysqld.sock :host: localhost test: <<: *default :database: dm2_test production: <<: *default :database: dm2_prod
  • 23. Create config/initializers/datamapper.rb require quot;dm-corequot; hash = YAML.load(File.new(Rails.root + quot;/config/database.ymlquot;)) DataMapper.setup(:default, 'mysql://root:mysql@localhost/dm2_dev' )
  • 24. Generate Model > script/generate dm_model book amount:float date:date name:string description:text --skip-migration NOTE: --skip-migration is needed because the rails-datamapper integration gem doesn't pull out the ActiveRecord dependency on migration creation yet.
  • 25. Finish model definition require 'lorem' class Book include DataMapper::Resource property :id, Integer, :serial => true property :amount, Float property :date, Date property :name, String property :description, Text, :lazy => true def self.create_dummy_data(num) num.times do |number| t = Book.new t.attributes = {:amount => number, :date => Time.now(), :name => Lorem.lorem(4, false), :description => Lorem.lorem(60, false)} t.save end end end
  • 26. Create Migration migration 1, :create_books do up do create_table :books do column :id, Integer, :serial => true, :nullable? => false, :key => true column :amount, Float column :date, Date column :name, String column :description, DataMapper::Types::Text end end down do drop_table :books end end
  • 27. Create Migration Rake Task namespace :dm do task :migrate => :environment do gem quot;dm-migrationsquot; require quot;migration_runnerquot; Dir[File.join(Rails.root, quot;dbquot;, quot;migratequot;, quot;*quot;)].each {|f| require f} migrate_up! end end src/dm2> mysqladmin create dm2_dev src/dm2> rake dm:migrate
  • 28. Wire up application ● Create Controller for book ● Create “bulk” generation capability
  • 29. Summary Checklist ● Add gems & generate application ● Remove ActiveRecord & add DataMapper ● Configure database.yml & datamapper.rb ● Create your database ● Generate your model, complete definition & migrate ● Continue defining application
  • 30. Additional Goodness ● Validations ● Conditions ● Order ● Aggregations ● Associations ● Named Scope (class methods)
  • 31. Assessment ● Can't beat the speed ● Outstanding flexibility ● Durn if it won't be more complex to develop with