Class: RestfulQuery::Sort

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/restful_query/sort.rb,
lib/sequel/extensions/restful_query.rb

Constant Summary collapse

DIRECTIONS =
{
  'up' => 'ASC',
  'asc' => 'ASC',
  'ASC' => 'ASC',
  'down' => 'DESC',
  'desc' => 'DESC',
  'DESC' => 'DESC'
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(column, direction, options = {}) ⇒ Sort

Returns a new instance of Sort.



19
20
21
22
23
# File 'lib/restful_query/sort.rb', line 19

def initialize(column, direction, options = {})
  self.column    = column
  self.direction = direction
  self.options = options
end

Instance Attribute Details

#columnObject

Returns the value of attribute column.



7
8
9
# File 'lib/restful_query/sort.rb', line 7

def column
  @column
end

#directionObject

Returns the value of attribute direction.



7
8
9
# File 'lib/restful_query/sort.rb', line 7

def direction
  @direction
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/restful_query/sort.rb', line 7

def options
  @options
end

Class Method Details

.next_direction(current_direction) ⇒ Object

Makes a roundabout for directions nil -> desc -> asc -> nil



63
64
65
66
67
68
69
70
71
72
# File 'lib/restful_query/sort.rb', line 63

def self.next_direction(current_direction)
  case current_direction.to_s.downcase
  when 'desc'
    'asc'
  when 'asc'
    nil
  else
    'desc'
  end
end

.parse(sort_string, split_on = /\-|\ /) ⇒ Object



25
26
27
28
29
# File 'lib/restful_query/sort.rb', line 25

def self.parse(sort_string, split_on = /\-|\ /)
  return unless sort_string
  column, direction, options = sort_string.split(split_on, 3)
  new(column, direction, options)
end

Instance Method Details

#==(other) ⇒ Object



57
58
59
60
# File 'lib/restful_query/sort.rb', line 57

def ==(other)
  return false unless other.is_a?(Sort)
  column == other.column && direction == other.direction
end

#next_directionObject



74
75
76
# File 'lib/restful_query/sort.rb', line 74

def next_direction
  self.class.next_direction(direction)
end

#reverse_directionObject



53
54
55
# File 'lib/restful_query/sort.rb', line 53

def reverse_direction
  direction == 'ASC' ? 'DESC' : 'ASC'
end

#to_s(join = '-') ⇒ Object



78
79
80
81
82
# File 'lib/restful_query/sort.rb', line 78

def to_s(join = '-')
  s = "#{column}#{join}#{direction.downcase}"
  s << " #{options.inspect}" unless options.empty?
  s
end

#to_sequelObject



6
7
8
# File 'lib/sequel/extensions/restful_query.rb', line 6

def to_sequel
  column.to_sym.send(direction.downcase)
end

#to_sqlObject



84
85
86
87
88
89
90
# File 'lib/restful_query/sort.rb', line 84

def to_sql
  sql = "#{column} #{direction}"
  unless options.empty?
    sql << ' ' << options.to_a.flatten.collect {|k| k.to_s.upcase }.join(' ')
  end
  sql
end