-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathsort_direction.rb
54 lines (46 loc) · 1.2 KB
/
sort_direction.rb
1
2
3
4
5
6
7
8
9
10
11
12
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
52
53
54
# frozen_string_literal: true
# Helper class for column sorting in Pagination.
#
# Examples:
#
# @direction = SortDirection.new(:asc)
# @direction.to_s # => "ASC"
# @direction.downcase # => 'asc'
# @direction.opposite # => 'DESC'
#
# SortDirection.new(:wrong).to_s # => 'ASC'
#
class SortDirection
##
# When given an unknown or nil direction, default to this value
DEFAULT_DIRECTION = 'ASC'
##
# Possible sort direction values
DIRECTIONS = %w[ASC DESC].freeze
##
# The direction represented as an uppercase, abbreviated String
attr_reader :direction
alias to_s direction
##
# The direction as uppercase
#
# Returns String
delegate :uppercase, to: :direction
##
# The direction as lowercase
#
# Returns String
delegate :downcase, to: :direction
# Initialize a new SortDirection
#
# direction - The direction (asc or desc) we want to sort results by
def initialize(direction = nil)
@direction = direction.to_s.upcase.presence_in(DIRECTIONS) || DEFAULT_DIRECTION
end
# The opposite direction to this one. Returns asc for desc, and desc for asc.
#
# Returns String
def opposite
@opposite ||= DIRECTIONS[DIRECTIONS.index(direction) - 1]
end
end