Class: Miscellany::SortLang::Parser
- Inherits:
-
Object
- Object
- Miscellany::SortLang::Parser
- Defined in:
- lib/miscellany/sort_lang.rb
Defined Under Namespace
Classes: SortParsingError
Instance Attribute Summary collapse
-
#default_sorts ⇒ Object
readonly
Returns the value of attribute default_sorts.
Instance Method Summary collapse
-
#initialize(valid_sorts, default: nil) ⇒ Parser
constructor
A new instance of Parser.
- #parse(sortstr, ignore_errors: true, default: :true) ⇒ Object
- #valid?(sortstr) ⇒ Boolean
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 = (valid_sorts) @default_sorts = [] parsed_defaults = (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_sorts ⇒ Object (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
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 |