Class: SqlBeautifier::SortExpression

Inherits:
Base
  • Object
show all
Defined in:
lib/sql_beautifier/sort_expression.rb

Constant Summary collapse

DIRECTION_PATTERN =
%r{\s+(asc|desc)(?:\s+(nulls\s+(?:first|last)))?\z}i
NULLS_ONLY_PATTERN =
%r{\s+(nulls\s+(?:first|last))\z}i

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse(text) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sql_beautifier/sort_expression.rb', line 12

def self.parse(text)
  stripped = text.strip

  direction_match = stripped.match(DIRECTION_PATTERN)
  if direction_match
    expression = stripped[0...direction_match.begin(0)].strip
    direction = direction_match[1].downcase
    nulls = direction_match[2]&.downcase&.squeeze(" ")
    return new(expression: expression, direction: direction, nulls: nulls)
  end

  nulls_match = stripped.match(NULLS_ONLY_PATTERN)
  if nulls_match
    expression = stripped[0...nulls_match.begin(0)].strip
    return new(expression: expression, nulls: nulls_match[1].downcase.squeeze(" "))
  end

  new(expression: stripped)
end

Instance Method Details

#render ⇒ Object



32
33
34
35
36
37
# File 'lib/sql_beautifier/sort_expression.rb', line 32

def render
  parts = [@expression]
  parts << @direction if @direction
  parts << @nulls if @nulls
  parts.join(" ")
end