module Elastics::Scopes::ClassMethods

Public Instance Methods

scope(name, scope=nil, &block) click to toggle source
define scopes as class methods

class MyModel

include Elastics::StoredModel
...
scope :red, terms(:color => 'red').sort(:supplier => :asc)
scope :size do |size|
  terms(:size => size)
end

MyModel.size('large').first
MyModel.red.all
MyModel.size('small').red.all
# File lib/elastics/scopes.rb, line 62
def scope(name, scope=nil, &block)
  raise ArgumentError, "Dangerous scope name: a :#{name} method is already defined. Please, use another one." \
        if respond_to?(name)
  proc = case
         when block_given?
           block
         when scope.is_a?(Elastics::Scope)
           lambda {scope}
         when scope.is_a?(Proc)
           scope
         else
           raise ArgumentError, "Scope object or Proc expected (got #{scope.inspect})"
         end
  metaclass = class << self; self end
  metaclass.send(:define_method, name) do |*args|
    scope = proc.call(*args)
    raise Scope::Error, "The scope :#{name} does not return a Elastics::Scope object (got #{scope.inspect})" \
          unless scope.is_a?(Elastics::Scope)
    scope
  end
  scope_methods << name
end
scoped() click to toggle source

You can start with a non restricted Elastics::Scope object

# File lib/elastics/scopes.rb, line 43
def scoped
  @scoped ||= Scope[:context => elastics.context, :self_context => self]
end