Method: Miscellany::SortLang::Parser#parse

Defined in:
lib/miscellany/sort_lang.rb

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



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

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