module Queryable

Public: Mixin that adds Queryable functionality to a plain ruby object.
A Queryable manages an internal query object, and defines chainable methods
that interact with the query object, modifying its value.
It's designed to work well with both Mongoid and ActiveRecord.

Examples

  class PersonQuery
    include Queryable
    scope(:too_damn_high) { where(:level.gt => 9000) }
  end

Public: Provides default configuration for query objects that decorate a ActiveRecord::Relation object, delegating the most used methods.

Public: Provides a class method that allows a method to be chained.

Public: Provides default initialization for query objects, most objects are mapped to a collection or table, the default query takes all of them.

Public: Allows to define default scopes in query objects, and inherit them in query object subclasses.

Public: Provides default configuration for query objects that decorate a Mongoid::Criteria object, delegating the most used methods in Criteria.

Public Class Methods

chained_method(name, accessor) click to toggle source

Internal: Generates a method that delegates the call to the an internal object, assigns the return value, and returns self.

Returns a String with the code of the method.

# File lib/queryable.rb, line 94
  def self.chained_method(name, accessor)
    <<-CHAIN
      def #{name}(*args, &block)
        @queryable = #{accessor}.__send__(:#{name}, *args, &block)
        self
      end
    CHAIN
  end
default_delegated_methods() click to toggle source

Internal: Default methods to be delegated to the internal query.

Returns an Array with the name of the methods to delegate.

# File lib/queryable.rb, line 106
def self.default_delegated_methods
  Array.instance_methods - Object.instance_methods + [:all, :==, :as_json, :decorate]
end
included(base) click to toggle source

Internal: Adds class methods, a query accessor, and method delegation.

# File lib/queryable.rb, line 16
def self.included(base)
  base.extend Forwardable
  base.extend ClassMethods
  base.class_eval do
    # Public: Gets/Sets the internal query.
    attr_accessor :queryable
    alias_method :query, :queryable

    # Internal: Delegates Array and Criteria methods to the internal query.
    delegate *Queryable.default_delegated_methods
  end
end
new(query) click to toggle source

Public: Initialize a Queryable with a query.

query - The internal query to build upon.

# File lib/queryable.rb, line 32
def initialize(query)
  @queryable = query.all
end