Sha256: 4ef47a2e3d537d5f299a1a6882b229a02a9dbfbe0fb036a57d2bbf19ffbd0d90

Contents?: true

Size: 1.26 KB

Versions: 81

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

module Motor
  module ApiQuery
    module Sort
      FIELD_PARSE_REGEXP = /\A(-)?(.*)\z/.freeze

      module_function

      def call(rel, param)
        return rel if param.blank?

        arel_order = build_arel_order(rel.klass, param)
        join_params = build_join_params(rel.klass, param)

        rel = rel.left_joins(join_params) if join_params.present?

        rel.reorder(arel_order)
      end

      def build_join_params(_model, param)
        param.split(',').each_with_object({}) do |field, result|
          key = field[FIELD_PARSE_REGEXP, 2]
          *path, _ = key.split('.')

          path.reduce(result) do |acc, fragment|
            hash = {}

            acc[fragment] = hash

            hash
          end
        end
      end

      def build_arel_order(model, param)
        param.split(',').map do |field|
          direction, key = field.match(FIELD_PARSE_REGEXP).captures
          *path, field = key.split('.')

          reflection_model =
            path.reduce(model) do |acc, fragment|
              acc.reflections[fragment].klass
            end

          arel_column = reflection_model.arel_table[field]

          direction.present? ? arel_column.desc : arel_column.asc
        end
      end
    end
  end
end

Version data entries

81 entries across 81 versions & 1 rubygems

Version Path
motor-admin-0.2.31 lib/motor/api_query/sort.rb
motor-admin-0.2.30 lib/motor/api_query/sort.rb
motor-admin-0.2.29 lib/motor/api_query/sort.rb
motor-admin-0.2.28 lib/motor/api_query/sort.rb
motor-admin-0.2.27 lib/motor/api_query/sort.rb
motor-admin-0.2.26 lib/motor/api_query/sort.rb
motor-admin-0.2.25 lib/motor/api_query/sort.rb
motor-admin-0.2.24 lib/motor/api_query/sort.rb
motor-admin-0.2.23 lib/motor/api_query/sort.rb
motor-admin-0.2.22 lib/motor/api_query/sort.rb
motor-admin-0.2.21 lib/motor/api_query/sort.rb
motor-admin-0.2.20 lib/motor/api_query/sort.rb
motor-admin-0.2.19 lib/motor/api_query/sort.rb
motor-admin-0.2.18 lib/motor/api_query/sort.rb
motor-admin-0.2.17 lib/motor/api_query/sort.rb
motor-admin-0.2.16 lib/motor/api_query/sort.rb
motor-admin-0.2.15 lib/motor/api_query/sort.rb
motor-admin-0.2.14 lib/motor/api_query/sort.rb
motor-admin-0.2.13 lib/motor/api_query/sort.rb
motor-admin-0.2.12 lib/motor/api_query/sort.rb