Module: UtilityScopes::Ordered::ClassMethods

Defined in:
lib/utility_scopes/ordered.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



68
69
70
71
72
73
74
75
# File 'lib/utility_scopes/ordered.rb', line 68

def method_missing(method, *args, &block)
  col = method.to_s.match(/^(order_by_|sort_by_)(.*)$/)[2] rescue false
  if col && self.columns.collect{ |c| c.name }.include?(col)
    return self.order_by(col, *args, &block)
  else
    super
  end
end

Instance Method Details

#ordered_by(clause) ⇒ Object

Decorate this class with the ability to order itself in queries either from a given parameter or from its default ordering:

class Article < ActiveRecord::Base
  ordered_by "published_at DESC"
end

Article.ordered #=> all items ordered by "published_at DESC"
Article.ordered('popularity ASC') #=> all items ordered by "popularity ASC"
Article.default_ordering #=> "published_at DESC"


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/utility_scopes/ordered.rb', line 47

def ordered_by(clause)
  # Override named scope on AR::Base so we can access default_ordering
  # on subclass
  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
    }
  })
  
  eigenclass.instance_eval do
    define_method(:default_ordering) { clause }
  end
end