Module: UtilityScopes::Ordered

Defined in:
lib/utility_scopes/ordered.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary (collapse)

Class Method Details

+ (Object) included(base)



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
# File 'lib/utility_scopes/ordered.rb', line 5

def self.included(base)
  base.extend ClassMethods
  
  base.class_eval do
    # Provide an ordered scope
    named_scope(:ordered, lambda { |*order|
      { :order => case
        when order.empty?
          self.default_ordering
        # allow hash support for jruby or ruby 1.9
        when order.size == 1 && order[0].is_a?(Hash) && (PLATFORM=~/java/ || RUBY_VERSION=~/1\.9.*/)
          order.first.collect{|(k,v)| "#{k} #{v.to_s.upcase}"}.join(', ')
        else
          order.collect{|e| e.is_a?(Array) ? "#{e[0]} #{e[1].to_s.upcase}" : e}.join(', ')
        end
      }
    })
    
    class << self
      # Set alias order_by
      alias_method :order_by, :ordered
      # Set alias sort_by
      alias_method :sort_by, :ordered
      # Set the default order
      define_method(:default_ordering) { 'created_at DESC' }
    end
  end
end