Class: Wallaby::Sorting::HashBuilder
- Inherits:
-
Object
- Object
- Wallaby::Sorting::HashBuilder
- Defined in:
- lib/services/wallaby/sorting/hash_builder.rb
Overview
Turn a string e.g.'name asc,id desc' into sort hash e.g.{name: 'asc', id: 'desc'}
Constant Summary collapse
- SORT_REGEX =
/(([^\s,]+)\s+(asc|desc))\s*,?\s*/i.freeze
Class Method Summary collapse
-
.build(sort_string) ⇒ Hash
Turn a string e.g.
'name asc,id desc'into sort hash e.g.{name: 'asc', id: 'desc'}. - .to_str(hash) ⇒ Object
Class Method Details
.build(sort_string) ⇒ Hash
Turn a string e.g.'name asc,id desc' into sort hash e.g.{name: 'asc', id: 'desc'}
12 13 14 15 16 |
# File 'lib/services/wallaby/sorting/hash_builder.rb', line 12 def self.build(sort_string) ::ActiveSupport::HashWithIndifferentAccess.new.tap do |hash| (sort_string || EMPTY_STRING).scan(SORT_REGEX) { |_, key, order| hash[key] = order } end end |
.to_str(hash) ⇒ Object
18 19 20 21 22 23 24 25 |
# File 'lib/services/wallaby/sorting/hash_builder.rb', line 18 def self.to_str(hash) hash.each_with_object(EMPTY_STRING.dup) do |(name, sort), str| next unless /\A(asc|desc)( nulls (first|last))?\Z/i.match?(sort) str << (str == EMPTY_STRING ? str : COMMA) str << name.to_s << SPACE << sort << (block_given? ? yield(name) : EMPTY_STRING) end end |