Module: OrderAsSpecified

Defined in:
lib/order_as_specified.rb,
lib/order_as_specified/error.rb,
lib/order_as_specified/version.rb

Overview

This module adds the ability to query an ActiveRecord class for results from the database in an arbitrary order, without having to store anything extra in the database. Simply ‘extend` it into your class and then you can use the `order_as_specified` class method.

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"1.7"

Instance Method Summary collapse

Instance Method Details

#order_as_specified(hash) ⇒ ActiveRecord::Relation

Returns the objects, ordered as specified.

Parameters:

  • hash (Hash)

    the ActiveRecord arguments hash

Returns:

  • (ActiveRecord::Relation)

    the objects, ordered as specified



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
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/order_as_specified.rb', line 13

def order_as_specified(hash)
  distinct_on = hash.delete(:distinct_on)
  case_insensitive = hash.delete(:case_insensitive)

  params = extract_params(hash)
  return all if params[:values].empty?

  table = Arel::Table.new(params[:table])
  node = Arel::Nodes::Case.new

  params[:values].each_with_index do |value, index|
    attribute = table[params[:attribute]]
    condition =
      if value.is_a?(Range)
        if value.first >= value.last
          raise OrderAsSpecified::Error, "Range needs to be increasing"
        end

        attribute.between(value)
      elsif case_insensitive
        attribute.matches(value)
      else
        attribute.eq(value)
      end

    node.when(condition).then(index)
  end

  node.else(node.conditions.size)
  scope = order(Arel::Nodes::Ascending.new(table.grouping(node)))

  if distinct_on
    distinct = Arel::Nodes::DistinctOn.new(node)
    table_alias = connection.quote_table_name(table.name)
    scope = scope.select(Arel.sql("#{distinct.to_sql} #{table_alias}.*"))
  end

  scope
end