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



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

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

#duplicates?(options) ⇒ Boolean

Returns:



48
49
50
# File 'lib/request_handler/sort_option_parser.rb', line 48

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

#fetch_optionsObject

Raises:



17
18
19
20
21
# File 'lib/request_handler/sort_option_parser.rb', line 17

def fetch_options
  raise SortParamsError.new([jsonapi_error("must not be empty")]) if empty_param?("sort")

  params.fetch("sort", "").split(",")
end

#parse_option(option) ⇒ Object

Raises:



32
33
34
35
36
37
38
39
40
# File 'lib/request_handler/sort_option_parser.rb', line 32

def parse_option(option)
  raise SortParamsError.new([jsonapi_error("must not contain spaces")]) if option.include? " "

  if option.start_with?("-")
    [option[1..], :desc]
  else
    [option, :asc]
  end
end

#parse_options(options) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/request_handler/sort_option_parser.rb', line 23

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
14
15
# 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.new([jsonapi_error("sort options must be unique")]) if duplicates?(sort_options)

  sort_options
end