aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/algebra/ordering.rb
blob: 8ed3e1e6e62b0a09bae64a5a6f60a6a85afe11d6 (plain) (blame)
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
module Arel
  class Ordering < Struct.new(:attribute)
    delegate :relation, :to => :attribute

    def bind(relation)
      self.class.new(attribute.bind(relation))
    end

    def to_ordering
      self
    end

    def == other
      super || (self.class === other && attribute == other.attribute)
    end

    def eval(row1, row2)
      (attribute.eval(row1) <=> attribute.eval(row2)) * direction
    end

    def to_sql(formatter = Sql::OrderClause.new(relation))
      formatter.ordering self
    end
  end

  class Ascending  < Ordering
    def direction; 1 end
    def direction_sql; 'ASC' end
  end

  class Descending < Ordering
    def direction_sql; 'DESC' end
    def direction; -1 end
  end
end