Module: Hurray::ClassMethods

Defined in:
lib/hurray.rb

Instance Method Summary collapse

Instance Method Details

#ordered_with(hash) ⇒ Object

Get records ordered according to the specified with array column order

Examples:

>> User.ordered_with(id: [4,2,6])
=> User::ActiveRecord_Relation [#<User id: 4 ...>, #<User id: 2 ...>, #<User id: 6 ...>, #<User id: 1 ...>, ...]

>> User.joins(:friends).ordered_with(friends: { id: [4, 2, 6] })

Arguments:

hash: (Hash)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/hurray.rb', line 17

def ordered_with(hash)
  params = []
  parse_ordered_with_params(hash, params)

  order_clause = ''
  params.each_with_index do |param, index|
    order_clause << ', ' if index != 0
    order_clause << "CASE #{param[:table]}.#{param[:column]} "
    array = param[:array]
    array.each_with_index do |el, pos|
      order_clause << sanitize_sql_array(['WHEN ? THEN ? ', el, pos])
    end
    order_clause << sanitize_sql_array(['ELSE ? END', array.length])
  end

  order(order_clause)
end