Class: Miscellany::SortLang::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/miscellany/sort_lang.rb

Defined Under Namespace

Classes: SortParsingError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(valid_sorts, default: nil) ⇒ Parser

Returns a new instance of Parser.



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/miscellany/sort_lang.rb', line 65

def initialize(valid_sorts, default: nil)
  @sorts_map = normalize_sort_options(valid_sorts)

  @default_sorts = []

  parsed_defaults = normalize_sort_options(Array(default))
  parsed_defaults.each do |k,v|
    @sorts_map[k] ||= v
  end
  @default_sorts = parsed_defaults.keys.map do |k|
    @sorts_map[k]
  end
end

Instance Attribute Details

#default_sortsObject (readonly)

Returns the value of attribute default_sorts.



63
64
65
# File 'lib/miscellany/sort_lang.rb', line 63

def default_sorts
  @default_sorts
end

Instance Method Details

#parse(sortstr, ignore_errors: true, default: :true) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/miscellany/sort_lang.rb', line 86

def parse(sortstr, ignore_errors: true, default: :true)
  sorts = (sortstr || '').split(',').map do |s|
    m = s.strip.match(/^(\w+)(?: (ASC|DESC))?$/)

    if m.nil?
      next if ignore_errors
      raise SortParsingError, message: 'Could not parse sort parameter'
    end

    resolved_sort = @sorts_map[m[1]]
    unless resolved_sort.present?
      next if ignore_errors
      raise SortParsingError, message: 'Could not parse sort parameter'
    end

    sort = resolved_sort.dup
    sort[:order] = m[2] if m[2].present? && !sort[:force_order]
    sort
  end

  if default == :append || default && !sorts.compact.present?
    sorts.push(*self.default_sorts)
  end

  sorts.compact.presence
end

#valid?(sortstr) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
82
83
84
# File 'lib/miscellany/sort_lang.rb', line 79

def valid?(sortstr)
  parse(sortstr, ignore_errors: false)
  true
rescue SortParsingError
  false
end