Class: Uchi::SortOrder

Inherits:
Object
  • Object
show all
Defined in:
lib/uchi/sort_order.rb

Overview

Encapsulates the sort order selected by a user.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column, direction) ⇒ SortOrder

Returns a new instance of SortOrder.



35
36
37
38
# File 'lib/uchi/sort_order.rb', line 35

def initialize(column, direction)
  @column = column.respond_to?(:asc) ? column : column.to_sym
  @direction = direction.to_sym
end

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



4
5
6
# File 'lib/uchi/sort_order.rb', line 4

def column
  @column
end

#directionObject (readonly)

Returns the value of attribute direction.



4
5
6
# File 'lib/uchi/sort_order.rb', line 4

def direction
  @direction
end

Class Method Details

.from_params(params) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/uchi/sort_order.rb', line 7

def from_params(params)
  sort_params = params[:sort] || {}
  return nil if sort_params.empty?

  by = sort_params[:by]
  return by unless by

  direction = sort_params[:direction] || :asc
  new(by, direction)
end

Instance Method Details

#apply(query) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/uchi/sort_order.rb', line 23

def apply(query)
  if column.respond_to?(:asc)
    query.order(ascending? ? column.asc : column.desc)
  else
    query.order(column => direction)
  end
end

#ascending?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/uchi/sort_order.rb', line 19

def ascending?
  direction == :asc
end

#descending?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/uchi/sort_order.rb', line 31

def descending?
  direction == :desc
end