Revisions

gist: 111783 Download_button fork
public
Public Clone URL: git://gist.github.com/111783.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module StrictlyUntyped
  module ConditionsScope
    # Makes it easy to add scopes which are only conditions.
    #
    # For example,
    # class Person < ActiveRecord::Base
    # named_scope :active, :conditions => {:active => true}
    # end
    #
    # Can be replaced with
    # named_conditions :active, :active => true
    #
    #
    # Also,
    # Person.scoped(:conditions => {:active => true})
    #
    # Can be replaced with
    # Person.conditions :active => true
    #
    def self.included(base)
      base.class_eval do
        extend ClassMethods
        named_conditions :conditions, lambda { |conditions| conditions }
      end
    end
    
    module ClassMethods
      def named_conditions(name, conditions, &block)
        named_scope(name, case conditions
            when Hash
              {:conditions => conditions}
            when Proc
              lambda { |*args| {:conditions => conditions.call(*args)} }
          end, &block)
      end
    end
  end
end