Sha256: bb4029e6bdf2756946698157dcd19fc0ca0238f51fc9fc58a6ab188723db1ed9

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module NamedScope
    # Creates a named_scope for the +Document+, similar to ActiveRecord's
    # named_scopes. +NamedScopes+ are proxied +Criteria+ objects that can be
    # chained.
    #
    # Example:
    #
    #   class Person
    #     include Mongoid::Document
    #     field :active, :type => Boolean
    #     field :count, :type => Integer
    #
    #     named_scope :active, :where => { :active => true }
    #     named_scope :count_gt_one, :where => { :count.gt => 1 }
    #     named_scope :at_least_count, lambda { |count| { :where => { :count.gt => count } } }
    #   end
    def named_scope(name, options = {}, &block)
      name = name.to_sym
      scopes[name] = lambda do |parent, *args|
        Scope.new(parent, options.scoped(*args), &block)
      end
      (class << self; self; end).class_eval <<-EOT
        def #{name}(*args)
          scopes[:#{name}].call(self, *args)
        end
      EOT
    end
    
    alias :scope :named_scope 

    alias :scope :named_scope

    # Return the scopes or default to an empty +Hash+.
    def scopes
      read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
    end

  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
mongoid-pre-2.0.0.beta1 lib/mongoid/named_scope.rb
mongoid-2.0.0.alpha lib/mongoid/named_scope.rb