Module: Queryable

Defined in:
lib/queryable.rb,
lib/queryable/default_query.rb,
lib/queryable/default_scope.rb

Overview

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

Defined Under Namespace

Modules: ClassMethods, DefaultQuery, DefaultScope

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_delegated_methodsObject

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

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



116
117
118
119
120
# File 'lib/queryable.rb', line 116

def self.default_delegated_methods
  Array.instance_methods - Object.instance_methods +
  [:all, :where, :distinct, :group, :having, :includes, :joins, :limit, :offset, :order, :reverse_order] +
  [:==, :as_json, :cache_key, :decorate]
end

.included(base) ⇒ Object

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



16
17
18
19
20
21
22
23
24
25
26
27
# 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

.scope_method(name) ⇒ Object

Internal: Generates the scope interceptor method.

name - Name of the method to convert to a scope.

Returns a String with the code of the scope method.



104
105
106
107
108
109
110
111
# File 'lib/queryable.rb', line 104

def self.scope_method(name)
  <<-SCOPE
    def #{name}(*args)
      @queryable = super
      self
    end
  SCOPE
end

Instance Method Details

#initialize(query) ⇒ Object

Public: Initialize a Queryable with a query.

query - The internal query to build upon.



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

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