Getting Started

Installation

The preferred method for installing Origin is with bundler. Simply add Origin to your Gemfile.

gem "origin", "~> 1.0.4"

Alternatively you can get the Origin gem direcly from rubygems.org:

$ gem install origin

Basics

Origin provides a DSL to mix in to any object to give it the ability to build MongoDB queries easily. Simply include the module Origin::Queryable to get started.

class Query
  include Origin::Queryable
end

The Queryable provides a default constructor that takes 2 optional parameters, a hash of aliased field mappings, and a hash of name and serializer pairs. We will discuss those options in the serialization and aliases sections.

Once you have your queryable object, you can begin creating queries.

query = Query.new
query.where(name: "Syd").desc(:name)

Each time a method on the queryable is called, it clones itself and returns a new copy with the next selection added. This is to not modify the previous queryable in case it needs reuse later on without the additional selection.

At any time you can ask the queryable for a selector or its options, which can then be used with your favourite driver to query the database for documents.

query = Query.new.where(name: "Syd").only(:name)

# With Moped
session[:users].find(query.selector).select(query.options.fields)

# With the 10gen driver
collection.find(query.selector, query.options)

The query's selector is a hash that represents the MongoDB selector.

query = Query.new
query = query.where(name: "Syd").between(age: 18..25)
query.selector #=> { "name" => "Syd", "age" => { "$gte" => 18, "$lte" => 25 }}

The query's options is a hash that represents various options that can be passed with a query, such as field limiting, skip, limit, and sorting options.

query = Query.new
query = query.only(:name).skip(10).limit(20).desc(:name)

query.options #=> { fields: { "name" => 1 }, skip: 10, limit: 20, sort: { "name" => -1 }}

query.options.fields #=> { "name" => 1 }
query.options.limit #=> 20
query.options.skip #=> 10
query.options.sort #=> { "name" => -1 }

Forwarding

In many cases for convenience you may not want to instantiate a new Queryable object manually, but provide an easier way to generate them from models. Origin provides a Origin::Forwardable module to allow you to specify a method to create queryables from, and subsequently injects all of its public API into the model in question.

class Query
  include Origin::Queryable
end

class Band
  extend Origin::Forwardable
  select_with :query

  def self.query
    Query.new
  end
end

Band.where(name: /^depeceh/i).gt(likes: 10000)
Band.nin(name: [ "New Order", "Pet Shop Boys" ]).asc(:likes)