Sha256: 5aac5b7f61036cedbb1f153a76297c92a80ae11cbd6de8a014bd36b927ca2a67

Contents?: true

Size: 1.35 KB

Versions: 2

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true
require 'request_handler/option_parser'
require 'request_handler/error'
require 'request_handler/sort_option'
module RequestHandler
  class SortOptionParser < OptionParser
    def run
      return [] unless params.key?('sort')
      sort_options = parse_options(fetch_options)
      raise ExternalArgumentError, sort_options: 'must be unique' if duplicates?(sort_options)
      sort_options
    end

    def fetch_options
      raise ExternalArgumentError, sort_options: 'the query paramter must not be empty' if empty_param?('sort')
      params.fetch('sort') { '' }.split(',')
    end

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

    def parse_option(option)
      raise ExternalArgumentError, sort_options: 'must not contain a space' if option.include? ' '
      if option.start_with?('-')
        [option[1..-1], :desc]
      else
        [option, :asc]
      end
    end

    def allowed_option(name)
      allowed_options_type.call(name)
    rescue Dry::Types::ConstraintError
      raise OptionNotAllowedError, name.to_sym => 'is not an allowed sort option'
    end

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
request_handler-0.11.0 lib/request_handler/sort_option_parser.rb
request_handler-0.10.0 lib/request_handler/sort_option_parser.rb