Learning Mongoid - Gautam Rege - E-Book

Learning Mongoid E-Book

Gautam Rege

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Mongoid helps you to leverage the power of schema-less and efficient document-based design, dynamic queries, and atomic modifier operations. Mongoid eases the work of Ruby developers while they are working on complex frameworks.

Starting with why and how you should use Mongoid, this book covers the various components of Mongoid. It then delves deeper into the detail of queries and relations, and you will learn some tips and tricks on improving performance. With this book, you will be able to build robust and large-scale web applications with Mongoid and Rails.

Starting with the basics, this book introduces you to components such as moped and origin, and how information is managed, learn about the various datatypes, embedded documents, arrays, and hashes. You will learn how a document is stored and manipulated with callbacks, validations, and even atomic updates. This book will then show you the querying mechanism in detail, right from simple to complex queries, and even explains eager loading, lazy evaluation, and chaining of queries. Finally, this book will explain the importance of performance tuning and how to use the right indexes. It also explains MapReduce and the Aggregation Framework.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 140

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Mongoid
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. What's so Awesome about Mongoid?
A practical approach using the Sodibee library system
Checking prerequisites
Ruby version
MongoDB version
Setting up Sodibee
Creating models
Testing the models
Introducing Moped
Dynamic attributes
Introducing Origin
Notice about Mongoid 2.x
Mongoid and MongoMapper
Summary
2. Mongoid Document Model
The Mongoid document
Basic attributes
Arrays and hashes
Date and time attributes
Serialization with Mongoize
Field aliases
Embedded documents
Localization
Mass assignment and security
Summary
3. Persisting Documents
MongoDB persistence strategy
Binary JSON (BSON)
Memory maps, delayed sync, and journals
Creating documents
Updating documents and attributes
Database locks and transactions
Applications and lock versioning
The MongoDB findAndModify method
Atomic attribute updates
Dynamic attributes
Nested attributes
Validations
Callbacks
Summary
4. Mongoid Relations
Configuring relationships
Common options for all relations
:class_name
:inverse_of
Relation-specific options
has_one – the one-to-one relation
:as
:autosave
:autobuild
:dependent
:primary_key
:foreign_key
:validate
has_many – the many-to-one relation
:order
:before_add, :after_add, :before_remove, and :after_remove
The belongs_to relation
:index
:polymorphic
:touch
:counter_cache
has_and_belongs_to_many – the many-to-many relation
:inverse_of
Polymorphic relations
embeds_many – embedding many documents
:cascade_callbacks
:store_as
:cyclic
embeds_one – embed one document
embedded_in – resolving children
Embedded polymorphic relations
Summary
5. Mongoid Queries
Origins of Origin
Query selectors
Overloading the Symbol class
Mongoid criteria
Queries on arrays and hashes
Scopes
Atomic modifiers
find_and_modify
Querying with indexed fields
Covered queries
The aggregation framework
Geolocation queries
Summary
6. Performance Tuning
MongoDB environment
Indexes
Write concern
Compound index
Multikey index
Hashed index
Text index
IdentityMap
n+1 query problem and eager loading
MapReduce and the aggregation framework
Using the aggregation framework
Choosing between MapReduce and the aggregation framework
Monitoring query performance
Profiling MongoDB
Statistical data
Hint and currentOp
Good practices and recommendations
Summary
7. Mongoid Modules
Timestamping
Versioning
Paranoia
Acts as state machine (aasm)
carrierwave
mongoid-audit
devise
Summary
Index

Learning Mongoid

Learning Mongoid

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2013

Production Reference: 1051213

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78216-750-1

www.packtpub.com

Cover Image by Aniket Sawant (<[email protected]>)

Credits

Author

Gautam Rege

Reviewers

Ravil Bayramgalin

Simone Carletti

Sergio Tulentsev

Acquisition Editors

Pramila Balan

Subho Gupta

Commissioning Editor

Govindan K

Technical Editors

Dipika Gaonkar

Kapil Hemnani

Nikhil Potdukhe

Copy Editors

Roshni Banerjee

Mradula Hegde

Dipti Kapadia

Kirti Pai

Lavina Pereira

Laxmi Subramanian

Project Coordinator

Joel Goveya

Proofreader

Chris Smith

Indexer

Monica Ajmera Mehta

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

About the Author

Gautam Rege is driven by his passion for programming, he co-founded Josh Software with Sethupathi Asokan in 2007. He still codes religiously and leads the marketing of the India-based Josh Software brand across the world, apart from being involved in delivering web solutions for the client partners of the organization. With more than 13 years of experience in the industry, he has handled a wide array of profiles that have helped him to develop strong analysis and project management skills, and an understanding of client partner needs for sustainable and high-standard web solutions.

He is an ardent promoter of Ruby on Rails and leads many of the brand's initiatives to promote this framework in India. He helps organize the annual RubyConf India, talks at Ruby conferences across the world, and manages local Ruby meetings. When not discussing Ruby, he loves talking about entrepreneurship and the importance of starting up young! Apart from being an active voice through his popular blog, he has authored the book Ruby and MongoDB Web Development Beginner's Guide, Packt Publishing. He truly believes that Ruby is the language of the next generation of web application development.

Before beginning his professional career in 2000, he completed his B.E. from the Pune Institute of Computer Technology (PICT). In his spare time, apart from spending time with his family, he is an athlete and loves playing cricket, basketball, and soccer when he can. He is always on the lookout to feed his hunger for adventure by going for activities such as skydiving and bungee jumping.

Writing your second book is always easier than the first because one is already tuned to write late in the night and on weekends. This book has a lot of input from practical experiences I had while working at Josh. Without the support of Sethu to free up my work so that I could find time to write this book, it may never have been completed!

My wife Vaibhavi and daughter Swara provided a lot of moral support and both were very patient even when I missed out on family time and family occasions. Thank you very much! The book reviewers and technical editors provided excellent feedback and suggestions that have helped in my work.

About the Reviewers

Simone Carletti has been working professionally with Ruby since 2006. He's very passionate about code quality and best practices.

He has been involved with free and open source software (FOSS) for more than a decade, contributing code and creating libraries in several different programming languages. The most recent projects are available in his GitHub account (weppos).

Currently, he is working as a Software Developer at DNSimple—a company providing DNS hosting, domain registration, and SSL certificates. His personal website is http://www.simonecarletti.com/.

Sergio Tulentsev is an early MongoDB adopter and Mongoid fan. He has used them to build systems that handle substantial load (greater than 100 million hits per day). He often speaks about MongoDB at conferences and even patched it once or twice.

When not fending off bears in snowy Russia, he travels, tries new kinds of food, and learns new languages.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Learning Mongoid gives beginners a good start to building a Rails application using MongoDB with Mongoid. For intermediate and expert Ruby developers, this book provides an excellent reference for using Mongoid. The book has plenty of examples with code samples and explanations that help in understanding the various features of Mongoid.

What this book covers

Chapter 1, What's so Awesome about Mongoid?, explains why Mongoid is one of the popular choices for Rails applications that use MongoDB. We are also introduced to Origin and Moped, which are integral parts of Mongoid.

Chapter 2, Mongoid Document Model, discusses the various data types that are supported by Mongoid and how they are stored. We learn about arrays, hashes, and embedded documents. We also briefly touch upon localized storage of string.

Chapter 3, Persisting Documents, discusses how documents are saved, format, optimization, and even managing custom data types and their serialization. We will also learn about atomic updates, callbacks, and validations.

Chapter 4, Mongoid Relations, explains the various relations that are supported by Mongoid, including One-to-One, One-to-Many, recursively embedded documents, and even polymorphic relations.

Chapter 5, Querying Attributes, explains everything about searching. We take a deep dive into how Origin works and how Mongoid criteria are managed. We learn about criteria chaining, lazy evaluation, and even eager loading of related documents.

Chapter 6, Performance Tuning, deals with how we can improve performance. We learn about the various indexes and when to use the right index. We see how the identity map can help in eager loading. Finally, we learn about MapReduce and the aggregation framework, which can drastically improve performance.

Chapter 7, Mongoid Modules, introduces various modules and gems available, which can help enhance the features with Mongoid. We learn about paranoid deletes, versioning, cloning, slugs, authentication, authorization using Devise, and even uploading documents using CarrierWave.

What you need for this book

This book assumes that you are using MacOS or Ubuntu Linux. It requires the latest MongoDB 2.4.x stable version, the latest Ruby 2.0 version, the latest Rails 4 version, and the latest Mongoid 4 version.

Who this book is for

This book is intended for beginners and experts alike. For a beginner, this book serves as an excellent guide for building Rails applications with Mongoid. For an intermediate or expert user, this book serves as an excellent reference for using the various features of Mongoid.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

class Address include Mongoid::Document field :street, type: String field :city, type: String field :state, type: String field :zipcode, type: String field :country, type: String embedded_in :author end

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

require File.expand_path('../boot', __FILE__) require "action_controller/railtie"require "action_mailer/railtie"require "sprockets/railtie"

Any command-line input or output is written as follows:

$ ruby –v

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. What's so Awesome about Mongoid?

The name MongoDB is derived from humongous. We use DataMappers to work with MongoDB. In Ruby, the most popular MongoDB mapper is Mongoid, pronounced mann-gyod. But is this the only mapper available? There also exists MongoMapper, MongoODM, and in the realm of open source there could well be many more!

So, what is so awesome about Mongoid? In a nutshell, its ability to gel with the Rails framework makes it very popular. For me, it is this adaptability to refactor and improve that makes Mongoid a very close ally of Rails.

In this chapter, we shall get a taste of the power of Mongoid. We shall see:

How Mongoid adheres to Rails ActiveModel and ActiveRelation syntaxDifferences between Mongoid Version 2.x and 3.xA brief introduction to Moped and OriginSome differences between MongoMapper and Mongoid and their usage

A practical approach using the Sodibee library system

Sodibee (pronounced saw-di-bee) is a library-management system that can manage books, reviews, authors, and bookings. Here are some of the functions that are supported in Sodibee:

An author has many books and a book belongs to an authorA book has many reviews and has one bookingA review belongs to a user and is about a bookA booking belongs to a user and a book

Note

In the course of this book we will be working with the latest versions of Ruby 2.0, Mongoid 4, Rails 4, and MongoDB 2.4.

Checking prerequisites

First and foremost, we need to ensure that we have our development environment set up. It's common to use multiple versions of Ruby for development; I use RVM to manage these versions. As we can have multiple versions of the same gem installed on our machines, we use RVM gemsets to manage the gems we need for our work.

Ruby version

To check the Ruby version, check the version that is installed using the following command:

$ rvm listrvm rubies jruby-1.7.4 [ x86_64 ] ruby-1.9.3-p385 [ x86_64 ]=* ruby-2.0.0—p247 [ x86_64 ]# => - current# =* - current && default# * - default$ ruby –vruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]

Note

Ruby 2.1 is due to be released in December, 2013. Everything in this book will be fully compatible with Ruby 2.1 too.

MongoDB version

We are currently using MongoDB v2.4.6—verify that, using the following command:

$ mongoMongoDB shell version: 2.4.6connecting to: test>

If you don't see this, it's quite likely that you have not installed MongoDB or it isn't running. Get going!

Setting up Sodibee

First and foremost, let's install the Rails gem.

$ gem install rails

This installs Rails 4.0.0.

Note

At the time of writing this book, the Rails version was 4.0.0. All commands would be fully compatible with the latest Rails version.

Now, let's create the Sodibee project.