CSC/ECE 517 Fall 2013/ch1 1w44 s: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
(Created page with "== '''Non-relational Databases in Rails Applications''' == Active Record is basic to Rails and it is responsible to for allowing programs to treat records in relational dbs as o...")
 
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
== '''Non-relational Databases in Rails Applications''' ==
== '''Non-relational Databases in Rails Applications''' ==


Active Record is basic to Rails and it is responsible to for allowing programs to treat records in relational dbs as objects. It employs Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. While Active Record is efficient in what it does, the complexities of ORM make way for a new approach for databases with rails, that is to move to different Database Models namely Object-Oriented Databases and No-SQL Databases.
Active Record is basic to Rails and it is responsible for allowing programs to treat records in relational databases as objects. It employs Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system (RDBMS). While Active Record is efficient in what it does, the complexities of ORM make way for a new approach for databases with rails, that is to move to different Database Models namely Object-Oriented Databases and No-SQL Databases.


__TOC__
__TOC__
Line 11: Line 11:
Rails uses the Active Record pattern which describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database.  
Rails uses the Active Record pattern which describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database.  


Active Record is the layer of the system responsible for representing business data and logic. It facilitates the creation and use of business objects whose data requires persistent storage to a database. It employs Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.
Active Record is the layer of the system responsible for representing business data and logic. It facilitates the creation and use of business objects whose data requires persistent storage to a database. It employs ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.


Active Record gives us several mechanisms, the most important being the ability to:
Active Record gives us several mechanisms, the most important being the ability to:
Line 24: Line 24:
The relational model on which Active Record relies on takes data and separates it into many interrelated tables that contain rows and columns. Tables reference each other through foreign keys that are stored in columns as well.  When looking up data, the desired information needs to be collected from many tables (often hundreds in today’s enterprise applications) and combined before it can be provided to the application. Similarly, when writing data, the write needs to be coordinated and performed on many tables.
The relational model on which Active Record relies on takes data and separates it into many interrelated tables that contain rows and columns. Tables reference each other through foreign keys that are stored in columns as well.  When looking up data, the desired information needs to be collected from many tables (often hundreds in today’s enterprise applications) and combined before it can be provided to the application. Similarly, when writing data, the write needs to be coordinated and performed on many tables.


The Active Record pattern describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database. The pattern has numerous limitations referred to as the Object-relational impedance mismatch. Some of these technical difficulties are structural. In OO programming, objects may be composed of other objects. The Active Record pattern maps these sub-objects to separate tables, thus introducing issues concerning the representation of relationships and encapsulated data. Active Record uses macros to create relationships between objects and single table inheritance to represent inheritance.
The Active Record pattern describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database. The pattern has numerous limitations referred to as the Object-relational impedance mismatch. Some of these technical difficulties are structural. In Object Oriented programming, objects may be composed of other objects. The Active Record pattern maps these sub-objects to separate tables, thus introducing issues concerning the representation of relationships and encapsulated data. Active Record uses macros to create relationships between objects and single table inheritance to represent inheritance.


Active Record is a solution for the Object-relational impedance mismatch, but this is assuming the datastore is relational. It’s also, fundamentally, a hack. The obvious cleaner solution being using a Object Oriented datastore.
Active Record is a solution for the Object-relational impedance mismatch, but this is assuming the datastore is relational. It’s also, fundamentally, a hack.


== '''Object Database''' ==
== '''Non Relational Databases''' ==
An object database (also object-oriented database management system). Object-Oriented Database Management System (OODBMS) is a Database Management System (DBMS) which allows information to be represented in the form of objects as used in object-oriented programming. OODBMSs provide an integrated application development environment by joining object-oriented programming with database technology. OODBMSs enforce object oriented programming concepts such as encapsulation, polymorphism and inheritance as well as database management concepts such as Atomicity, Consistency, Isolation and Durability. Since both the programming language and OODBMS use the same object-oriented model, the programmers can maintain the consistency easily between the two environments.
=== '''Object Database''' ===
An object database also known as Object-Oriented Database Management System (OODBMS) is a Database Management System (DBMS) which allows information to be represented in the form of objects as used in object-oriented programming. OODBMSs provide an integrated application development environment by joining object-oriented programming with database technology. OODBMSs enforces object oriented programming concepts such as encapsulation, polymorphism and inheritance as well as database management concepts such as Atomicity, Consistency, Isolation and Durability. Since both the programming languages and OODBMS use the same object-oriented model, the programmers can maintain the consistency easily between the two environments.


== '''Comparison with RDBMS''' ==
==== '''Comparing RDBMS with Object Database''' ====
{| class="wikitable"
|-
! Criteria !! RDBMS !! OODBMS
|-
| Object-oriented programming support || Poor || Extensive
|-
| Ease of Use || Table schemas easy to understand for everyone || Good for Programmers only
|-
| Ease in development || Independent from application || Objects are a natural way to model, can incorporate types and relationships
|-
| Extensiblity || Low || High
|-
| Data relationships || Hard to model || Easy to handle
|-
| Maturity || Very Mature || Relatively Mature
|}
 
=== '''No-SQL Databases''' ===
A NoSQL database provides a mechanism for storage and retrieval of data that is less constrained in its consistency models than traditional Relational Databases.
 
NoSQL encompasses a wide variety of different database technologies but generally all NoSQL databases have a few features in common.
*'''Dynamic Schemas'''
Relational databases require that schemas be defined before you can add data. This fits poorly with agile development approaches, because each time you complete new features, the schema of your database often needs to change. Furthermore, if the database is large, this is a very slow process that involves significant downtime.
In contrast NoSQL databases are built to allow the insertion of data without a predefined schema. That makes it easy to make significant application changes in real-time, without worrying about service interruptions – which means development is faster, code integration is more reliable, and less database administrator time is needed.
*'''Sharding, Replication and Caching'''
Because of the way they are structured, relational databases usually scale vertically. This gets expensive quickly, places limits on scale and is failure prone.
The solution is to scale horizontally, by adding servers instead of concentrating more capacity in a single server. NoSQL databases usually support auto-sharding, automatic replication, meaning that you get high availability and finally caching capabilities.
 
NoSQL Database Types
:Document databases
:Graph stores
:Key-value stores
:Wide-column stores
 
==== '''Comparing No-SQL DB with RDBMS'''<ref>http://www.couchbase.com/why-nosql/nosql-database</ref> ====
Relational and Object database models are very different.  
Relational and Object database models are very different.  
For example, a document-oriented OODBMS takes the data you want to store and aggregates it into documents using the JSON format. Each JSON document can be thought of as an object to be used by your application. A JSON document might, for example, take all the data stored in a row that spans 20 tables of a relational database and aggregate it into a single document/object. Aggregating this information may lead to duplication of  information, but since storage is no longer cost prohibitive, the resulting data model flexibility, ease of efficiently distributing the resulting documents and read and write performance improvements make it an easy trade-off for web-based applications.
For example, a document-oriented database takes the data you want to store and aggregates it into documents using the JSON format. Each JSON document can be thought of as an object to be used by your application. A JSON document might, for example, take all the data stored in a row that spans 20 tables of a relational database and aggregate it into a single document/object. Aggregating this information may lead to duplication of  information, but since storage is no longer cost prohibitive, the resulting data model flexibility, ease of efficiently distributing the resulting documents and read and write performance improvements make it an easy trade-off for web-based applications.


[[File:nosqlvsrdbms.jpg|frame|none|alt=Document Object Model equivalent to Relational tables|Document Object Model equivalent to Relational tables]]
[[File:nosqlvsrdbms.jpg|frame|none|alt=Document Object Model equivalent to Relational tables|Document Object Model equivalent to Relational tables<ref>http://www.couchbase.com/why-nosql/nosql-database</ref>]]


Another major difference is that relational technologies have rigid schemas. Relational technology requires strict definition of a schema prior to storing any data into a database. Changing the schema once data is inserted is a big deal, extremely disruptive and frequently avoided.
Another major difference is that relational databases have rigid schemas. Relational databases requires strict definition of a schema prior to storing any data into a database. Changing the schema once data is inserted is a big deal, extremely disruptive and frequently avoided.
In comparison, document databases are schemaless, allowing you to freely add fields to JSON documents without having to first define changes. The format of the data being inserted can be changed at any time, without application disruption.
In comparison, document databases are schemaless, allowing you to freely add fields to JSON documents without having to first define changes. The format of the data being inserted can be changed at any time, without application disruption.


== '''Examples in Rails Apps''' ==


In this section we will see how to incorporate two Document Object Databases MongoDB and CouchDB in a rails application. We will also explore Embedding and Nesting for models to better exhibit their use.


=== Naming Guidelines<ref>http://itsignals.cascadia.com.au/?p=7</ref> ===
=== '''MongoDB'''<ref>http://docs.mongodb.org/</ref> ===
----
Ruby uses the first character of the name to help it determine it’s intended use.
The standard Ruby file extension is .rb, although many people working on [http://en.wikipedia.org/wiki/Unix UNIX]-like systems don't bother with it for stand-alone scripts. Whether or not one uses it for scripts is up to them, but they will need to use it for library files or they will not be found by the interpreter.


*'''Local Variables'''
MongoDB is a document database that provides high performance, high availability, and easy scalability. Key features:
:Should use lowercase letter followed by other characters. Naming convention states that it is better to use underscores rather than [http://en.wikipedia.org/wiki/CamelCase camelBack] for multiple word names, e.g. average, variable_xyz
*'''Flexibility'''
*'''Instance Variables'''
MongoDB stores data in JSON documents (which we serialize to BSON). JSON provides a rich data model that seamlessly maps to native programming language types, and the dynamic schema makes it easier to evolve your data model than with a system with enforced schemas such as a RDBMS.
:Instance variables are defined using the single "at" sign (@) followed by a name. It is suggested that a lowercase letter should succeed @, e.g. @color
*'''Power'''
*'''Instance Methods'''
MongoDB provides a lot of the features of a traditional RDBMS such as secondary indexes, dynamic queries, sorting, rich updates, upserts (update if document exists, insert if it doesn’t), and easy aggregation. This gives you the breadth of functionality that you are used to from an RDBMS, with the flexibility and scaling capability that the non-relational model allows.
:Method names should start with a lowercase letter, and may be followed by digits, underscores, and letters. The name should possibly be a verb e.g. move, display_details
*'''Speed/Scaling'''
*'''Class Variables'''
By keeping related data together in documents, queries can be much faster than in a relational database where related data is separated into multiple tables and then needs to be joined later. MongoDB also makes it easy to scale out your database. Autosharding allows you to scale your cluster linearly by adding more machines. It is possible to increase capacity without any downtime, which is very important on the web when load can increase suddenly and can bring down the website. Thus leading to extended maintenance which can cost large amounts of revenue.
:Class variable names start with a double "at" sign (@@) and may be followed by digits, underscores, and letters, e.g. @@color
*'''Ease of use'''
*'''Constant'''
MongoDB works hard to be very easy to install, configure, maintain, and use. To this end, MongoDB provides few configuration options, and instead tries to automatically do the “right thing” whenever possible. This means that MongoDB works right out of the box, and you can dive right into developing your application, instead of spending a lot of time fine-tuning obscure database configurations.
:Constant names usually start with an uppercase letter followed by other characters. Constant objects are by convention named using all uppercase letters and underscores between words, e.g. THIS_IS_A_CONSTANT
*'''Class and Module'''  
:Class names are recommended to be be nouns. In the case of modules, it's harder to make a clear recommendation. The names of [http://en.wikipedia.org/wiki/Mixin mix-ins] (which are just modules), however, should probably be adjectives, such as the standard [http://en.wikibooks.org/wiki/Ruby_Programming/Reference/Objects/Enumerable Enumerable] and [http://www.ruby-doc.org/core-2.0.0/Comparable.html Comparable] modules. Class and module names starts with an uppercase letter, by convention they are named using MixedCase, e.g. module Encryption, class MixedCase
*'''Global Variables'''
:Starts with a dollar ($) sign followed by other characters, e.g. $global


Considering customer order information as the data being used for an application, below naming guidelines give an idea of good class/table/file names.
A MongoDB deployment hosts a number of databases. A database holds a set of collections. A collection holds a set of documents. A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.
*'''Model Naming Convention'''
 
MongoDB stores all data in documents, which are JSON-style data structures composed of field-and-value pairs:
<pre>
<pre>
Table: orders
{ "item": "pencil", "qty": 500, "type": "no.2" }
Class: Order
File: /app/models/order.rb
Primary Key: id
Foreign Key: customer_id
Link Tables: items_orders
</pre>
</pre>


*'''Controller Naming Convention'''
MongoDB stores documents on disk in the BSON serialization format. BSON is a binary representation of JSON documents, though contains more data types than does JSON
 
MongoMapper and Mongoid are the two leading gems that make it possible to use MongoDB as a datastore with Rails. MongoMapper is a simple ORM for MongoDB. Mongoid’s goal is to provide a familiar API to Active Record, while still leveraging MongoDB’s advantages of schema flexibility, document design, atomic modifiers, and rich query interface.
 
==== '''MongoDB in Rails'''<ref>http://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/</ref> ====
 
Firstly to create a new Rails app using MongoDB we need to ensure we create it without active record and install the necessary gems outlined before.
<pre>
<pre>
Class: OrdersController
> rails new my_app --skip-active-record
File: /app/controllers/orders_controller.rb
> cd my_app
Layout: /app/layouts/orders.html.erb
> gem install mongo
> gem install bson
> gem install bson_ext
> gem install mongomapper
> gem install mongoid
> rails server
</pre>
</pre>
*'''View Naming Convention'''
 
Rails model files are altered to not have the classes inherit from ActiveRecord::Base, instead must include a module MongoMapper::Document, and define the schema in the actual file. Database migrations are not necessary.
<pre>
<pre>
Helper: /app/helpers/orders_helper.rb
class Story
Helper Module: OrdersHelper
include MongoMapper::Document
Views: /app/views/orders/… (list.html.erb for example)
 
</pre>
key :title,    String
*'''Tests Naming Convention'''
key :url,      String
<pre>
key :voters,    Array
Unit: /test/unit/order_test.rb
key :votes,    Integer, :default => 0
Functional: /test/functional/orders_controller_test.rb
 
Fixtures: /test/fixtures/orders.yml
# Cached values.
</pre>
key :comment_count, Integer, :default => 0
key :username,      String


=== Class Design Guidelines ===
# Note this: ids are of class ObjectId.
----
key :user_id,  ObjectId
timestamps!


A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. Class Customer can be displayed as:
# Relationships.
belongs_to :user


<pre>
# Validations.
class Customer
validates_presence_of :title, :url, :user_id
end
end
</pre>
</pre>


A class is terminated by using the keyword end. All the data members in the class are between the class definition and the end keyword.  
Additionally, you have a number of configuration options available, such as allow_dynamic_fields that allows you to define attributes on an object that aren’t in the model file’s schema. You can then add some logic in your model file if you need to do something different depending on the existence or absence of this field.


Ruby blurs the distinction between design and implementation. Ideas that have to be expressed at the design level in other languages can be implemented directly in Ruby. To help in this process, Ruby has support for some design-level strategies. These strategies can be used to design classes accordingly as suitable for different types of  applications.
For fast lookups, we can create an index on this field. In the MongoDB shell:
<pre>
db.courses.ensureIndex('voters');
</pre>


*'''[http://en.wikipedia.org/wiki/Visitor_pattern The Visitor pattern]''' is a way of traversing a collection without having to know the internal organization of that collection.
To find all the Courses by name:
*'''[http://en.wikipedia.org/wiki/Delegation_pattern Delegation]''' is a way of composing classes more flexibly and dynamically than can be done using standard inheritance.
<pre>
*The '''[http://en.wikipedia.org/wiki/Singleton_pattern Singleton pattern]''' is a way of ensuring that only one instantiation of a particular class exists at a time.
Course.all(:conditions => {:name => @suject.name})
*The '''[http://en.wikipedia.org/wiki/Observer_pattern Observer pattern]''' implements a protocol allowing one object to notify a set of interested objects when certain changes have occurred.
</pre>
 
Normally, all four of these strategies require explicit code each time they're implemented. With Ruby, they can be abstracted into a library and reused freely and transparently.


=== Member Design Guidelines ===
==== '''Embedding'''<ref>http://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/</ref> ====
----
Now we will see how we can acheive embedding in a Rails App that uses MongoDB. We do this by example, incorporating comments into the Story example illustrated above.
While defining class members, it is very important to keep in mind the access restrictions. Scope and life-time of class members are different for different restrictions, as illustrated below.
In a relational database, comments are usually given their own table, related by foreign key to some parent table. This approach is occasionally necessary in MongoDB; however, it’s always best to try to embed first, as this will achieve greater query efficiency.


*'''Linear Comments'''
<pre>
<pre>
public
class Story
totally accessible.
   include MongoMapper::Document
protected
   many :comments
accessible only by instances of class and direct descendants. Even through hasA relationships. (see below)
private
accessible only by instances of class (must be called nekkid no “self.” or anything else).
class A
  # Restriction used w/o arguments set the default access control.
   protected
 
  def protected_method
    # nothing
   end
end
end


class B < A
class Comment
   def test_protected
   include MongoMapper::EmbeddedDocument
    myA = A.new
   key :body, String
    myA.protected_method
   end


   # Used with arguments, sets the access of the named methods and constants.
   belongs_to :story
  public :test_protected
end
end
</pre>


b = B.new.test_protected
If we were using the Ruby driver alone, we could save our structure like so:
<pre>
@stories  = @db.collection('stories')
@document = {:title => "MongoDB on Rails",
            :comments => [{:body    => "Revelatory! Loved it!",
                            :username => "Matz"
                          }
                          ]
            }
@stories.save(@document)
</pre>
</pre>


=== Maintainability Guidelines ===
*'''Nested Comments'''
----
To build threaded comments:
Maintainability guidelines are important to programmers for a number of reasons:
<pre>
<blockquote>
@stories  = @db.collection('stories')
*40%-80% of the lifetime cost of a piece of software goes to maintenance.
@document = {:title => "MongoDB on Rails",
*Hardly any software is maintained for its whole life by the original author.
            :comments => [{:body    => "Revelatory! Loved it!",
*Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
                            :username => "Matz",
*If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.  
                            :comments => [{:body    => "Agreed.",
</blockquote>
                                          :username => "rubydev29"
The following guidelines are to be followed to improve the software maintainability
                                          }
* '''Profile your code regularly'''
                                        ]
: If you profile your code regularly you’ll be able to tell if the latest change to the code will have an adverse effect on performance. Integrate profiling into your testing process and make it automated to ensure that it’s not forgotten.  Like unit testing and BDD([http://en.wikipedia.org/wiki/Behavior-driven_development Behavior-driven development]) profiling goes a long way.
                          }
                          ]
            }
@stories.save(@document)
</pre>


=== Performance Guidelines<ref>http://blog.monitis.com/index.php/2012/02/08/20-ruby-performance-tips/</ref> ===
We can also represent comments as their own collection. Relative to the other options, this incurs a small performance penalty while granting us the greatest flexibility. The tree structure can be represented by storing the unique path for each leaf.
----
<pre>
The key parameter on which a software application is rated is by its performance. It is the time taken by the application to respond to a user's request. Performance of ruby can be improved significantly by following certain coding guidelines, as below.
class Comment
  include MongoMapper::Document


*'''Avoid nesting loops more than three levels deep'''
  key :body,      String
: Nesting affects the performance of the code proportionally with the increasing levels in loops. Limiting nesting to three levels is one good practice to keep the code's performance well.
  key :depth,      Integer, :default => 0
  key :path,      String,  :default => ""


*'''Avoid unnecessary variable assignments'''
  # Note: we're intentionally storing parent_id as a string
: New programmers, often use unwanted variables in code. A great example is when someone defines a variable to store a return value and then returns that variable; just return the value directly.
  key :parent_idString
  key :story_id,  ObjectId
  timestamps!


*'''Reduce usage of disk I/O'''
  # Relationships.
: Disk I/O is a very costly operation as far as computing is concerned. Keeping it to the minimal improves the application response time drastically. Using disk I/O, makes the application extremely slow. Using storage systems such as memcached reduces disk I/O operations to a great extent as lot of data is kept in memory. The speed improvement while using a memory caching system is tremendous.
  belongs_to :story


*'''Use Ruby Enterprise Edition'''
  # Callbacks.
: Ruby Enterprise edition provides up to [http://www.rubyenterpriseedition.com/faq.html#thirty_three_percent_mem_reduction 33% lower memory] usage.  Though, to get benefited by this performance one needs to follow their guidelines.
  after_create :set_path


*'''Avoid method calls as much as possible'''
  private
: Method calls are expensive operations in ruby. They should be avoided to keep up the performance of the application.


*'''Use interpolated strings instead of concatenated strings'''
  # Store the comment's path.
: Concatenated strings calls a method to get executed. So, it affects the performance as it is one of the most frequently used operation. Its better to replace them with Interpolated strings which runs faster as it doesn't invoke a method call.
  def set_path
<pre>
  ....
put “Hello there, #{name}!”vs.puts “Hello there, ” << name = “!”
    end
    save
  end
</pre>
</pre>


*'''Destructive operations are faster'''
=== '''CouchDB''' ===
: Ruby’s in-place methods that which modifies the actual value than working on a copy of the data are much faster. But this should be handled carefully as original data gets disturbed.
CouchDB is often categorized as a “NoSQL” database. A CouchDB database lacks a schema, or rigid pre-defined data structures such as tables.
A CouchDB server hosts named databases stores documents. Data stored in CouchDB is a JSON document(s). The structure of the data, or document(s), can change dynamically to accommodate evolving needs. Each document is uniquely named in the database, and CouchDB provides a RESTful HTTP API for reading and updating (add, edit, delete) database documents.
Documents are the primary unit of data in CouchDB and consist of any number of fields and attachments. Documents also include metadata that’s maintained by the database system. Document fields are uniquely named and contain values of varying types (text, number, boolean, lists, etc), and there is no set limit to text size or element count.
User can just chuck arbitrary JSON objects up at this thing and it’ll store it. No setup, no schemas, no nothing.


*'''Avoid unnecessary calls to uniq on arrays'''
: In many cases methods are already calling uniq on an array and there’s no need for you to call it yet again.


*'''For loops are faster than .each'''
Key Charachteristics
: .each uses an enumeration object behind the scene which adds a delay in execution. Using for instead of .each would improve performance but for short loops only.<ref>http://stackoverflow.com/questions/6406112/why-are-ruby-method-calls-particularly-slow-in-comparison-to-other-languages</ref>


*'''Use x.blank? over x.nil? || x.empty?'''
*'''Documents'''
: When using ActionPack there’s no need for x.nil? or x.empty?; x.blank? checks for both of these.
A CouchDB document is a JSON object that consists of named fields. Field values may be strings, numbers, dates, or even ordered lists and associative maps. An example of a document would be:
 
<pre>
*'''Avoid calls to parse_date and strftime'''
{
: Both these calls are very expensive. using regular expressions would improve the time.
    "Subject": "Foo Bar",
 
    "Author": "John Doe",
*'''Know your gems'''
    "PostedDate": "10/7/2013",
: All libraries are not efficient. Many gems may need to be removed to problem to fix a problem with the code. This is a common scenario when many gems are installed. So performing bench marking and testing a gem with others that perform same task would help in picking the right gem.
    "Tags": ["foo", "bar"],
    "Body": "Lorem Ipsum..."
}
</pre>
A CouchDB database is a flat collection of these documents. Each document is identified by a unique ID.


*'''Improve your algorithms before you try to improve your code'''
*'''Views'''
: Algorithmic improvements results in evident improvements in performance of the code. It is always ideal to design an efficient algorithm without unwanted method calls.
To address this problem of adding structure back to semi-structured data, CouchDB integrates a view model using JavaScript for description. Views are the method of aggregating and reporting on the documents in a database, and are built on-demand to aggregate, join and report on database documents. Views are built dynamically and don’t affect the underlying document; you can have as many different view representations of the same data as you like. Incremental updates to documents do not require full re-indexing of views.


*'''Test the most frequently occurring case first'''
*'''Schema Free'''
: While using if statements or a case statement always test the cases that occur most frequently. This allows less code to run before a decision is made. It may not seem like much but over several hundred or thousand runs through the decision logic you’ll notice a definite performance gain.
Unlike SQL databases, which are designed to store and report on highly structured, interrelated data, CouchDB is designed to store and report on large amounts of semi-structured, document oriented data. CouchDB greatly simplifies the development of document oriented applications, such as collaborative web applications.


*'''Optimize the way you access global constants'''
In an SQL database, the schema and storage of the existing data must be updated as needs evolve. With CouchDB, no schema is required, so new document types with new meaning can be safely added alongside the old. However, for applications requiring robust validation of new documents custom validation functions are possible. The view engine is designed to easily handle new document types and disparate but similar documents.
: While accessing the global constants one should use namespace before the constants to avoid entire library search for the constant.
*'''Use explicit returns'''
: Even though the result of last operation is returned for a method, using explicit returns would speed up the code. Explicit returns are faster, especially in older Ruby versions such as 1.8.x.


=== Documentation Guidelines<ref>http://guides.rubyonrails.org/api_documentation_guidelines.html</ref> ===
*'''Distributed'''
----
CouchDB is a peer based distributed database system. Any number of CouchDB hosts (servers and offline-clients) can have independent "replica copies" of the same database, where applications have full database interactivity (query, add, edit, delete). When back online or on a schedule, database changes can be replicated bi-directionally.


Documentation comments<ref>http://www.jetbrains.com/ruby/webhelp/documenting-source-code-in-rubymine.html</ref> can be created in accordance with [http://rdoc.sourceforge.net/ RDoc] and [http://yardoc.org/ YARD] syntax. Note that RDoc highlighting in documentation comments can be turned enabled or disabled in the Appearance page of the editor settings.
CouchDB has built-in conflict detection and management and the replication process is incremental and fast, copying only documents changed since the previous replication. Most applications require no special planning to take advantage of distributed updates and replication.


The most common Documentation guidelines are listed below.
==== '''CouchDB on Rails'''<ref>http://www.couchrest.info/</ref> ====
*Write simple, declarative sentences. Brevity is a plus: get to the point.
Installing CouchDB.
*Write in present tense: "Returns a hash that...", rather than "Returned a hash that..." or "Will return a hash that...".
*Start comments in upper case. Follow regular punctuation rules:
<pre>
<pre>
# Declares an attribute reader backed by an internally-named
sudo apt-get install couchdb -y
# instance variable.
def attr_internal_reader(*attrs)
  ...
end
</pre>
</pre>
*Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the idioms recommended in edge. Reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.
Or we can use the many pre compiled binaries on the CouchDB website.


Documentation has to be concise but comprehensive. Explore and document edge cases.
After installation, check if everything works fine by sending a curl request
<pre>
$ curl http://localhost:5984


=== Layout Guidelines<ref>http://www.caliban.org/ruby/rubyguide.shtml</ref> ===
{"couchdb":"Welcome","version":"1.1.1"}
----
</pre>
Designing the layout of any application determines the readability factor for other developers.
Most followed order of code is as follows:


We now install the Couchrest gem for ruby
<pre>
<pre>
header block with author's name, Perforce Id tag and a brief description of what the program or library is for.
gem install couchrest
require statements
include statements
class and module definitions
main program section
</pre>
</pre>


*'''Spreading Code Out and Lining it Up'''
To create a new model, we need to define a class that inherits from the CouchRest::Model::Base class in much the same way as an ActiveRecord model. Unlike a regular database mapper, CouchRest Model requires you to define the properties or attributes your model needs to use directly in the class. There are no migrations or automatic column detection in a Document Database.
:This is very important for readability. Basically the principle is to:
<pre>
:*separate each component part by white space.
class Person < CouchRest::Model::Base
:*align everything meaningfully.
  use_database 'people'
:As such one can easily scan up and down the code and see the patterns. This is very important not only for understanding the code, but also for looking for anomalies and as a tool for rationalizing and consolidating the code.
  property :first_name, String
:Code that has a lot of 'noise' - a lot of unnecessary variation and untidiness - is code that one can waste a lot of time working on. Well written and formatted code is code that is easy and quick to work with. It is code that allows one to easily 'see the wood from the trees'.
  property :last_name, String
 
  timestamps!
== '''Code Analysis Tools''' ==
  belongs_to :person
  collection_of :tags
end
</pre>
CouchDB is accessed via HTTP requests, as such, there is no requirement to create a binary connection to a specific database. The use_database method tells the model which database it should use. This can be provided as a CouchRest::Database object or as simple string that will be concatenated to the connection prefix. A special property macro is available called timestamps! that will create the created_at and updated_at accessors.


Ruby itself goes a long way towards helping developers write clear code.
As you’d expect, CouchRest Model supports all the standard CRUD operations you’re used to in other object mappers. CouchRest Model supports a few basic queries for retrieving your data from the database.


*'''The Ruby debugger''' is a library loaded into Ruby at run-time.  
==== '''Embedding'''<ref>http://www.couchrest.info/</ref> ====
This is done as follows:
The CouchRest Model Embeddable module allows you to take full advantage of CouchDB’s ability to store complex documents and retrieve them. Simply include the module in a Class and set any properties you’d like to use.
<pre>
<pre>
ruby -r debug [
class CatToy
            options
  include CouchRest::Model::Embeddable
            ] [
            programfile
            ] [
            arguments
            ]
</pre>


The debugger can do all the usual things one would expect it to, such as set breakpoints, step into and over code, print out the call stack, etc.
  property :name, String
  property :purchased, Date
end


While tools for the mainstream languages such as Java and C++ have reached a certain maturity, tools for Ruby are still growing. And they might be needed more and more as Ruby's usage spreads from early adopters to the early majority, and SLOC (Source Lines Of Code) continues to increase. Automatic tools<ref>http://www.ruby-toolbox.com/categories/code_metrics</ref> can be used to detect several types of problems including inconsistent style, long methods and repeated code.
class Cat < CouchRest::Model::Base
  property :name, String
  property :toys, CatToy, :array => true
end


*[http://github.com/roodi/roodi/tree/master '''Roodi'''] (Ruby Object Oriented Design Inferometer) - this parses Ruby code and warns about design issues from the list  configured, ie: Class line count check, for loop check, parameter number check, cyclomatic checks and 10 other checks
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchased => 1.month.ago}])
*[http://github.com/troessner/reek '''Reek'''] - similar in concept to Roodi
@cat.toys.first.class == CatToy
*[http://saikuro.rubyforge.org/ '''Saikuro'''] - designed to check cyclomatic complexity
@cat.toys.first.name == 'mouse'
*[http://ruby.sadi.st/Flog.html '''Flog'''] - created by Ryan Davis, this computes a score of code written: the higher the score is, the worse your code is. ABC metrics (Assignments, Branches and Calls) are taken into account to compute the score
</pre>
*[http://www.harukizaemon.com/simian/ '''Simian'''] - a similarity analyzer, this can be used for duplication identification (a $99 license is needed for commercial use)
*[http://ruby.sadi.st/Flay.html '''Flay'''] - this is another free tool from Ryan Davis that finds structural similarities in code


[[File:Code Analysis Outputs.png|frame|none|alt=Code Analysis Tool Results|Code Analysis Tool Results]]
nosqlvsrdbms.jpg
== '''Summary''' ==
== '''Summary''' ==
Ruby developers should follow a certain criteria or guidelines during software development. Coding standards are set of rules, guidelines and regulations on the manner of writing a code that helps programmers and developers read and understand quickly the source code that conforms to style and help avoid introducing misunderstanding and faults.
While Active Record's ORM is most prevelant other forms of databases provide considerable advantage over RDBMS. Other alternatives help us address issues such as scalability, flexibility and are more in-tune with the Cloud model of deploying apps.
 
Particularly in Ruby development, coding standards are extremely important; therefore Ruby developers should put an importance to them. This is because these standards offer higher uniformity and consistency when writing code by different programmers. This could result in a code that's simple to know and preserve, thus reducing the project’s overall expenses.
 
Some of the benefits of using coding standards are:
 
*Easy to understand and maintained
*Boost the code’s readability
*Maintainable applications
*Eradicates complexity
*Separate documents look more appropriate


== '''See Also''' ==
== '''See Also''' ==
*http://www.caliban.org/ruby/rubyguide.shtml
*http://mongoid.org/en/mongoid/index.html
*http://github.com/styleguide/ruby
*http://mongomapper.com/
*http://www.ruby-doc.org/docs/ProgrammingRuby/
*http://en.wikipedia.org/wiki/Object_database
*http://www.ruby-lang.org/en/documentation/
*http://www.mongodb.org/
*http://en.wikibooks.org/wiki/Ruby_programming_language
*http://couchdb.apache.org/
 
== '''References''' ==
== '''References''' ==
<references/>
<references/>

Latest revision as of 00:51, 8 October 2013

Non-relational Databases in Rails Applications

Active Record is basic to Rails and it is responsible for allowing programs to treat records in relational databases as objects. It employs Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system (RDBMS). While Active Record is efficient in what it does, the complexities of ORM make way for a new approach for databases with rails, that is to move to different Database Models namely Object-Oriented Databases and No-SQL Databases.

Overview

Rails, as a web development framework, and Ruby, as a programming language, can be used with a choice of operating systems (Linux, Mac OS X, Windows), databases (SQLite, MySQL, PostgreSQL, and others), and web servers (Apache, Nginx, and others). The Rails stack can also include a variety of software libraries (gems) that add features to a website or make development easier. Sometimes the choice of components in a stack is driven by the requirements of an application

Rails uses the Active Record pattern which describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database.

Active Record is the layer of the system responsible for representing business data and logic. It facilitates the creation and use of business objects whose data requires persistent storage to a database. It employs ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.

Active Record gives us several mechanisms, the most important being the ability to:

Represent models and their data.
Represent associations between these models.
Represent inheritance hierarchies through related models.
Validate models before they get persisted to the database.
Perform database operations in an object-oriented fashion.

Object-relational impedance mismatch

The relational model on which Active Record relies on takes data and separates it into many interrelated tables that contain rows and columns. Tables reference each other through foreign keys that are stored in columns as well. When looking up data, the desired information needs to be collected from many tables (often hundreds in today’s enterprise applications) and combined before it can be provided to the application. Similarly, when writing data, the write needs to be coordinated and performed on many tables.

The Active Record pattern describes the mapping of an object instance to a row in a relational database table, using accessor methods to retrieve columns/properties, and the ability to create, update, read, and delete entities from the database. The pattern has numerous limitations referred to as the Object-relational impedance mismatch. Some of these technical difficulties are structural. In Object Oriented programming, objects may be composed of other objects. The Active Record pattern maps these sub-objects to separate tables, thus introducing issues concerning the representation of relationships and encapsulated data. Active Record uses macros to create relationships between objects and single table inheritance to represent inheritance.

Active Record is a solution for the Object-relational impedance mismatch, but this is assuming the datastore is relational. It’s also, fundamentally, a hack.

Non Relational Databases

Object Database

An object database also known as Object-Oriented Database Management System (OODBMS) is a Database Management System (DBMS) which allows information to be represented in the form of objects as used in object-oriented programming. OODBMSs provide an integrated application development environment by joining object-oriented programming with database technology. OODBMSs enforces object oriented programming concepts such as encapsulation, polymorphism and inheritance as well as database management concepts such as Atomicity, Consistency, Isolation and Durability. Since both the programming languages and OODBMS use the same object-oriented model, the programmers can maintain the consistency easily between the two environments.

Comparing RDBMS with Object Database

Criteria RDBMS OODBMS
Object-oriented programming support Poor Extensive
Ease of Use Table schemas easy to understand for everyone Good for Programmers only
Ease in development Independent from application Objects are a natural way to model, can incorporate types and relationships
Extensiblity Low High
Data relationships Hard to model Easy to handle
Maturity Very Mature Relatively Mature

No-SQL Databases

A NoSQL database provides a mechanism for storage and retrieval of data that is less constrained in its consistency models than traditional Relational Databases.

NoSQL encompasses a wide variety of different database technologies but generally all NoSQL databases have a few features in common.

  • Dynamic Schemas

Relational databases require that schemas be defined before you can add data. This fits poorly with agile development approaches, because each time you complete new features, the schema of your database often needs to change. Furthermore, if the database is large, this is a very slow process that involves significant downtime. In contrast NoSQL databases are built to allow the insertion of data without a predefined schema. That makes it easy to make significant application changes in real-time, without worrying about service interruptions – which means development is faster, code integration is more reliable, and less database administrator time is needed.

  • Sharding, Replication and Caching

Because of the way they are structured, relational databases usually scale vertically. This gets expensive quickly, places limits on scale and is failure prone. The solution is to scale horizontally, by adding servers instead of concentrating more capacity in a single server. NoSQL databases usually support auto-sharding, automatic replication, meaning that you get high availability and finally caching capabilities.

NoSQL Database Types

Document databases
Graph stores
Key-value stores
Wide-column stores

Comparing No-SQL DB with RDBMS<ref>http://www.couchbase.com/why-nosql/nosql-database</ref>

Relational and Object database models are very different. For example, a document-oriented database takes the data you want to store and aggregates it into documents using the JSON format. Each JSON document can be thought of as an object to be used by your application. A JSON document might, for example, take all the data stored in a row that spans 20 tables of a relational database and aggregate it into a single document/object. Aggregating this information may lead to duplication of  information, but since storage is no longer cost prohibitive, the resulting data model flexibility, ease of efficiently distributing the resulting documents and read and write performance improvements make it an easy trade-off for web-based applications.

Document Object Model equivalent to Relational tables
Document Object Model equivalent to Relational tables<ref>http://www.couchbase.com/why-nosql/nosql-database</ref>

Another major difference is that relational databases have rigid schemas. Relational databases requires strict definition of a schema prior to storing any data into a database. Changing the schema once data is inserted is a big deal, extremely disruptive and frequently avoided. In comparison, document databases are schemaless, allowing you to freely add fields to JSON documents without having to first define changes. The format of the data being inserted can be changed at any time, without application disruption.

Examples in Rails Apps

In this section we will see how to incorporate two Document Object Databases MongoDB and CouchDB in a rails application. We will also explore Embedding and Nesting for models to better exhibit their use.

MongoDB<ref>http://docs.mongodb.org/</ref>

MongoDB is a document database that provides high performance, high availability, and easy scalability. Key features:

  • Flexibility

MongoDB stores data in JSON documents (which we serialize to BSON). JSON provides a rich data model that seamlessly maps to native programming language types, and the dynamic schema makes it easier to evolve your data model than with a system with enforced schemas such as a RDBMS.

  • Power

MongoDB provides a lot of the features of a traditional RDBMS such as secondary indexes, dynamic queries, sorting, rich updates, upserts (update if document exists, insert if it doesn’t), and easy aggregation. This gives you the breadth of functionality that you are used to from an RDBMS, with the flexibility and scaling capability that the non-relational model allows.

  • Speed/Scaling

By keeping related data together in documents, queries can be much faster than in a relational database where related data is separated into multiple tables and then needs to be joined later. MongoDB also makes it easy to scale out your database. Autosharding allows you to scale your cluster linearly by adding more machines. It is possible to increase capacity without any downtime, which is very important on the web when load can increase suddenly and can bring down the website. Thus leading to extended maintenance which can cost large amounts of revenue.

  • Ease of use

MongoDB works hard to be very easy to install, configure, maintain, and use. To this end, MongoDB provides few configuration options, and instead tries to automatically do the “right thing” whenever possible. This means that MongoDB works right out of the box, and you can dive right into developing your application, instead of spending a lot of time fine-tuning obscure database configurations.

A MongoDB deployment hosts a number of databases. A database holds a set of collections. A collection holds a set of documents. A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

MongoDB stores all data in documents, which are JSON-style data structures composed of field-and-value pairs:

{ "item": "pencil", "qty": 500, "type": "no.2" }

MongoDB stores documents on disk in the BSON serialization format. BSON is a binary representation of JSON documents, though contains more data types than does JSON

MongoMapper and Mongoid are the two leading gems that make it possible to use MongoDB as a datastore with Rails. MongoMapper is a simple ORM for MongoDB. Mongoid’s goal is to provide a familiar API to Active Record, while still leveraging MongoDB’s advantages of schema flexibility, document design, atomic modifiers, and rich query interface.

MongoDB in Rails<ref>http://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/</ref>

Firstly to create a new Rails app using MongoDB we need to ensure we create it without active record and install the necessary gems outlined before.

> rails new my_app --skip-active-record
> cd my_app
> gem install mongo
> gem install bson
> gem install bson_ext
> gem install mongomapper
> gem install mongoid
> rails server

Rails model files are altered to not have the classes inherit from ActiveRecord::Base, instead must include a module MongoMapper::Document, and define the schema in the actual file. Database migrations are not necessary.

class Story
 include MongoMapper::Document

 key :title,     String
 key :url,       String
 key :voters,    Array
 key :votes,     Integer, :default => 0

 # Cached values.
 key :comment_count, Integer, :default => 0
 key :username,      String

 # Note this: ids are of class ObjectId.
 key :user_id,   ObjectId
 timestamps!

 # Relationships.
 belongs_to :user

 # Validations.
 validates_presence_of :title, :url, :user_id
end

Additionally, you have a number of configuration options available, such as allow_dynamic_fields that allows you to define attributes on an object that aren’t in the model file’s schema. You can then add some logic in your model file if you need to do something different depending on the existence or absence of this field.

For fast lookups, we can create an index on this field. In the MongoDB shell:

db.courses.ensureIndex('voters');

To find all the Courses by name:

Course.all(:conditions => {:name => @suject.name})

Embedding<ref>http://docs.mongodb.org/ecosystem/tutorial/model-data-for-ruby-on-rails/</ref>

Now we will see how we can acheive embedding in a Rails App that uses MongoDB. We do this by example, incorporating comments into the Story example illustrated above. In a relational database, comments are usually given their own table, related by foreign key to some parent table. This approach is occasionally necessary in MongoDB; however, it’s always best to try to embed first, as this will achieve greater query efficiency.

  • Linear Comments
class Story
  include MongoMapper::Document
  many :comments
end

 class Comment
  include MongoMapper::EmbeddedDocument
  key :body, String

  belongs_to :story
end

If we were using the Ruby driver alone, we could save our structure like so:

@stories  = @db.collection('stories')
@document = {:title => "MongoDB on Rails",
             :comments => [{:body     => "Revelatory! Loved it!",
                            :username => "Matz"
                           }
                          ]
            }
@stories.save(@document)
  • Nested Comments

To build threaded comments:

@stories  = @db.collection('stories')
@document = {:title => "MongoDB on Rails",
             :comments => [{:body     => "Revelatory! Loved it!",
                            :username => "Matz",
                            :comments => [{:body     => "Agreed.",
                                           :username => "rubydev29"
                                          }
                                         ]
                           }
                          ]
            }
@stories.save(@document)

We can also represent comments as their own collection. Relative to the other options, this incurs a small performance penalty while granting us the greatest flexibility. The tree structure can be represented by storing the unique path for each leaf.

class Comment
  include MongoMapper::Document

  key :body,       String
  key :depth,      Integer, :default => 0
  key :path,       String,  :default => ""

  # Note: we're intentionally storing parent_id as a string
  key :parent_id,  String
  key :story_id,   ObjectId
  timestamps!

  # Relationships.
  belongs_to :story

  # Callbacks.
  after_create :set_path

  private

  # Store the comment's path.
  def set_path
  ....
    end
    save
  end

CouchDB

CouchDB is often categorized as a “NoSQL” database. A CouchDB database lacks a schema, or rigid pre-defined data structures such as tables. A CouchDB server hosts named databases stores documents. Data stored in CouchDB is a JSON document(s). The structure of the data, or document(s), can change dynamically to accommodate evolving needs. Each document is uniquely named in the database, and CouchDB provides a RESTful HTTP API for reading and updating (add, edit, delete) database documents. Documents are the primary unit of data in CouchDB and consist of any number of fields and attachments. Documents also include metadata that’s maintained by the database system. Document fields are uniquely named and contain values of varying types (text, number, boolean, lists, etc), and there is no set limit to text size or element count. User can just chuck arbitrary JSON objects up at this thing and it’ll store it. No setup, no schemas, no nothing.


Key Charachteristics

  • Documents

A CouchDB document is a JSON object that consists of named fields. Field values may be strings, numbers, dates, or even ordered lists and associative maps. An example of a document would be:

{
    "Subject": "Foo Bar",
    "Author": "John Doe",
    "PostedDate": "10/7/2013",
    "Tags": ["foo", "bar"],
    "Body": "Lorem Ipsum..."
}

A CouchDB database is a flat collection of these documents. Each document is identified by a unique ID.

  • Views

To address this problem of adding structure back to semi-structured data, CouchDB integrates a view model using JavaScript for description. Views are the method of aggregating and reporting on the documents in a database, and are built on-demand to aggregate, join and report on database documents. Views are built dynamically and don’t affect the underlying document; you can have as many different view representations of the same data as you like. Incremental updates to documents do not require full re-indexing of views.

  • Schema Free

Unlike SQL databases, which are designed to store and report on highly structured, interrelated data, CouchDB is designed to store and report on large amounts of semi-structured, document oriented data. CouchDB greatly simplifies the development of document oriented applications, such as collaborative web applications.

In an SQL database, the schema and storage of the existing data must be updated as needs evolve. With CouchDB, no schema is required, so new document types with new meaning can be safely added alongside the old. However, for applications requiring robust validation of new documents custom validation functions are possible. The view engine is designed to easily handle new document types and disparate but similar documents.

  • Distributed

CouchDB is a peer based distributed database system. Any number of CouchDB hosts (servers and offline-clients) can have independent "replica copies" of the same database, where applications have full database interactivity (query, add, edit, delete). When back online or on a schedule, database changes can be replicated bi-directionally.

CouchDB has built-in conflict detection and management and the replication process is incremental and fast, copying only documents changed since the previous replication. Most applications require no special planning to take advantage of distributed updates and replication.

CouchDB on Rails<ref>http://www.couchrest.info/</ref>

Installing CouchDB.

sudo apt-get install couchdb -y

Or we can use the many pre compiled binaries on the CouchDB website.

After installation, check if everything works fine by sending a curl request

$ curl http://localhost:5984

{"couchdb":"Welcome","version":"1.1.1"}

We now install the Couchrest gem for ruby

gem install couchrest

To create a new model, we need to define a class that inherits from the CouchRest::Model::Base class in much the same way as an ActiveRecord model. Unlike a regular database mapper, CouchRest Model requires you to define the properties or attributes your model needs to use directly in the class. There are no migrations or automatic column detection in a Document Database.

class Person < CouchRest::Model::Base
  use_database 'people'
  property :first_name, String
  property :last_name, String
  timestamps!
  belongs_to :person
  collection_of :tags
end

CouchDB is accessed via HTTP requests, as such, there is no requirement to create a binary connection to a specific database. The use_database method tells the model which database it should use. This can be provided as a CouchRest::Database object or as simple string that will be concatenated to the connection prefix. A special property macro is available called timestamps! that will create the created_at and updated_at accessors.

As you’d expect, CouchRest Model supports all the standard CRUD operations you’re used to in other object mappers. CouchRest Model supports a few basic queries for retrieving your data from the database.

Embedding<ref>http://www.couchrest.info/</ref>

The CouchRest Model Embeddable module allows you to take full advantage of CouchDB’s ability to store complex documents and retrieve them. Simply include the module in a Class and set any properties you’d like to use.

class CatToy
  include CouchRest::Model::Embeddable

  property :name, String
  property :purchased, Date
end

class Cat < CouchRest::Model::Base
  property :name, String
  property :toys, CatToy, :array => true
end

@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchased => 1.month.ago}])
@cat.toys.first.class == CatToy
@cat.toys.first.name == 'mouse'

Summary

While Active Record's ORM is most prevelant other forms of databases provide considerable advantage over RDBMS. Other alternatives help us address issues such as scalability, flexibility and are more in-tune with the Cloud model of deploying apps.

See Also

References

<references/>