Class: RequestHandler::SortOptionParser

Inherits:
OptionParser show all
Defined in:
lib/request_handler/sort_option_parser.rb

Instance Method Summary collapse

Methods inherited from OptionParser

#initialize

Constructor Details

This class inherits a constructor from RequestHandler::OptionParser

Instance Method Details

#allowed_option(name) ⇒ Object



38
39
40
41
42
# File 'lib/request_handler/sort_option_parser.rb', line 38

def allowed_option(name)
  RequestHandler.configuration.validation_engine.validate!(name, allowed_options_type).output
rescue Validation::Error
  raise OptionNotAllowedError, [jsonapi_error("#{name} is not an allowed sort option")]
end

#duplicates?(options) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/request_handler/sort_option_parser.rb', line 44

def duplicates?(options)
  !options.uniq!(&:field).nil?
end

#fetch_optionsObject

Raises:



15
16
17
18
# File 'lib/request_handler/sort_option_parser.rb', line 15

def fetch_options
  raise SortParamsError, [jsonapi_error('must not be empty')] if empty_param?('sort')
  params.fetch('sort') { '' }.split(',')
end

#parse_option(option) ⇒ Object

Raises:



29
30
31
32
33
34
35
36
# File 'lib/request_handler/sort_option_parser.rb', line 29

def parse_option(option)
  raise SortParamsError, [jsonapi_error('must not contain spaces')] if option.include? ' '
  if option.start_with?('-')
    [option[1..-1], :desc]
  else
    [option, :asc]
  end
end

#parse_options(options) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/request_handler/sort_option_parser.rb', line 20

def parse_options(options)
  options.map do |option|
    name, order = parse_option(option)
    name.gsub!('.', ::RequestHandler.configuration.separator)
    allowed_option(name)
    SortOption.new(name, order)
  end
end

#runObject

Raises:



8
9
10
11
12
13
# File 'lib/request_handler/sort_option_parser.rb', line 8

def run
  return [] unless params.key?('sort')
  sort_options = parse_options(fetch_options)
  raise SortParamsError, [jsonapi_error('sort options must be unique')] if duplicates?(sort_options)
  sort_options
end