Sha256: b43d7f8e5ba11df62da58624d4265a2497759dc9cd632fa7a97ee0aab65e7652

Contents?: true

Size: 775 Bytes

Versions: 1

Compression:

Stored size: 775 Bytes

Contents

# frozen_string_literal: true

module JSONAPIHelpers
  module Params
    module Sort
      def self.build(sort, allowed, default)
        allowed = allowed.map(&:to_s)
        fields = sort.to_s.split(',')

        ordered_fields = convert_to_ordered_hash(fields)
        filtered_fields = ordered_fields.select { |key, _value| allowed.include?(key) }
        filtered_fields.empty? ? default : filtered_fields
      end

      def self.convert_to_ordered_hash(fields)
        fields.each_with_object({}) do |field, hash|
          if field.start_with?('-')
            field = StringSupport.underscore(field[1..-1])
            hash[field] = :desc
          else
            hash[StringSupport.underscore(field)] = :asc
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsonapi_helpers-0.2.0 lib/jsonapi_helpers/params/sort.rb