class Wallaby::Sorting::NextBuilder

Generate sort param for given field's next sort order (e.g. from empty to `asc`, from `asc` to `desc`, from `desc` to empty)

Constants

ASC
DESC

Public Class Methods

new(params, hash = nil) click to toggle source

@param params [ActionController::Parameters] @param hash [Hash, nil] a hash containing sorting info, e.g. `{ name: 'asc' }`

# File lib/services/wallaby/sorting/next_builder.rb, line 13
def initialize(params, hash = nil)
  @params = params
  @hash = hash.try(:with_indifferent_access) || HashBuilder.build(params[:sort])
end

Public Instance Methods

next_params(field_name) click to toggle source

Update the `sort` parameter. @example for param `{sort: 'name asc'}`, it updates the parameters to:

{sort: 'name desc'}

@param field_name [String] field name @return [ActionController::Parameters]

updated parameters with new sort order for given field
# File lib/services/wallaby/sorting/next_builder.rb, line 24
def next_params(field_name)
  params = Utils.clone @params
  params[:sort] = complete_sorting_str_with field_name
  params
end

Protected Instance Methods

complete_sorting_str_with(field_name) click to toggle source

@param field_name [String] field name @return [String] a sort order string, e.g. `'name asc'`

# File lib/services/wallaby/sorting/next_builder.rb, line 34
def complete_sorting_str_with(field_name)
  hash = @hash.except field_name
  current_sort = @hash[field_name]
  hash[field_name] = next_value_for current_sort
  rebuild_str_from hash
end
next_value_for(current) click to toggle source

@param current [String, nil] current sort order @return [String, nil] next sort order

# File lib/services/wallaby/sorting/next_builder.rb, line 54
def next_value_for(current)
  case current
  when ASC then DESC
  when DESC then nil
  else ASC
  end
end
rebuild_str_from(hash) click to toggle source

@param hash [Hash] sort order hash @return [String] a sort order string, e.g. `'name asc'`

# File lib/services/wallaby/sorting/next_builder.rb, line 43
def rebuild_str_from(hash)
  hash.each_with_object(EMPTY_STRING.dup) do |(name, sort), str|
    next unless sort

    str << (str == EMPTY_STRING ? str : COMMA)
    str << name.to_s << SPACE << sort
  end
end