Class: DataTables::Modules::Order

Inherits:
Object
  • Object
show all
Defined in:
lib/data_tables/modules/order.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, scope, params) ⇒ Order

Returns a new instance of Order.



7
8
9
10
11
# File 'lib/data_tables/modules/order.rb', line 7

def initialize(model, scope, params)
  @scope = scope.dup
  @model = model
  @params = params
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



5
6
7
# File 'lib/data_tables/modules/order.rb', line 5

def context
  @context
end

#scopeObject (readonly)

Returns the value of attribute scope.



5
6
7
# File 'lib/data_tables/modules/order.rb', line 5

def scope
  @scope
end

Instance Method Details

#build_order(model, in_hash, join_hash = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/data_tables/modules/order.rb', line 25

def build_order(model, in_hash, join_hash = nil)
  # Tuple!
  return in_hash.inject([]) { |sum, (k, h)|
    case h
    when Hash
      if (klass = model.reflect_on_association(k).try(:klass))

        new_sum, join_class = build_order(klass, h)

        join_hash = join_class.nil? ? [k] : {k => join_class}

        sum += new_sum
      else
        warn("trying to reflect on #{k} but #{model.class.name} has no such association.")
      end
    else
      sum << model.arel_table[k].send(h) if model.column_names.include?(k.to_s)
    end
    sum
  }, join_hash
end

#orderObject



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/data_tables/modules/order.rb', line 13

def order
  columns = orderable_columns(@params[:order], @params[:columns])

  orders = DataTables::Responder.flat_keys_to_nested columns

  order_by, join_hash = build_order(@model, orders)

  @scope = @scope.joins(join_hash)

  order_by.inject(@scope) { |r, o| r.order(o) }
end