Class: Terrazzo::Order

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

Constant Summary collapse

VALID_DIRECTIONS =
%w[asc desc].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute: nil, direction: nil) ⇒ Order

Returns a new instance of Order.



7
8
9
10
# File 'lib/terrazzo/order.rb', line 7

def initialize(attribute: nil, direction: nil)
  @attribute = attribute&.to_sym
  @direction = normalize_direction(direction)
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



3
4
5
# File 'lib/terrazzo/order.rb', line 3

def attribute
  @attribute
end

#directionObject (readonly)

Returns the value of attribute direction.



3
4
5
# File 'lib/terrazzo/order.rb', line 3

def direction
  @direction
end

Instance Method Details

#apply(relation, dashboard) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/terrazzo/order.rb', line 12

def apply(relation, dashboard)
  return relation unless attribute

  type = dashboard.attribute_type_for(attribute)

  return relation if type.respond_to?(:sortable?) && !type.sortable?

  if type.respond_to?(:associative?) && type.associative?
    order_by_association(relation, type)
  else
    relation
      .order(attribute => direction)
      .order(relation.model.primary_key => :asc)
  end
end

#order_params_for(attr) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/terrazzo/order.rb', line 28

def order_params_for(attr)
  new_direction = if attr.to_sym == attribute
    direction == :asc ? :desc : :asc
  else
    :asc
  end

  { order: attr.to_s, direction: new_direction.to_s }
end

#ordered_by?(attr) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/terrazzo/order.rb', line 38

def ordered_by?(attr)
  attribute == attr.to_sym
end