Module: Queryable

Defined in:
lib/queryable.rb

Overview

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

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

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



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/queryable.rb', line 16

def self.included(base)
  base.extend ClassMethods
  base.extend Forwardable
  base.class_eval do

    # Public: Gets/Sets the internal query.
    attr_accessor :query

    def_delegators :query, *delegated_methods
  end
end

Instance Method Details

#define_queryObject

Public: Convenience setter for the internal query that returns self. The query is set to the value returned by the block. Useful when you need to access the context of the Queryable in addition to the query.

block - A block that returns the new value of the internal query.

Yields the internal query, which can be used to build upon.

def search(query)

Examples

# Accessing a constant in the Queryable object context.
LATEST_COUNT = 10
def latest
  define_query {|query| query.limit(LATEST_COUNT) }
end

# We use it because the last method we chain does not return self.
def recent_by_name
  define_query { recent.order(:name) }
end

# Extracted from a scope for clarity.
def search(field_values)
  define_query do |users|
    field_values.inject(users) { |users, (field, value)|
      users.where(field => /#{value}/i)
    }
  end
end

Returns the Queryable object itself (self).



67
68
69
70
# File 'lib/queryable.rb', line 67

def define_query
  @query = yield(query)
  self
end

#initialize(query) ⇒ Object

Public: Initialize a Queryable with a query.

query - The internal query to build upon.



31
32
33
# File 'lib/queryable.rb', line 31

def initialize(query)
  @query = query.all
end