Sha256: 50357a92fa4eecf9e32c02a804fb25c914b5b18485bb296b7b9d27063e85b768

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

module Katalyst
  module Tables
    module Collection
      # Adds sorting support to a collection.
      #
      # Sorting will be applied if the collection is configured with a default
      # sorting configuration by either specifying
      # `config.sorting = "column direction"` or passing
      # `sorting: "column direction"` to the initializer.
      #
      # If `sort` is present in params it will override the default sorting.
      module Sorting
        extend ActiveSupport::Concern

        included do
          config_accessor :sorting
          attr_accessor :sorting

          attribute :sort, :string
        end

        def initialize(sorting: config.sorting, **options)
          @sorting = SortForm.parse(sorting, default: sorting) if sorting

          super(sort: @sorting.to_param, **options) # set default sort based on config
        end

        def sort=(value)
          return unless @sorting

          # update internal proxy
          @sorting = SortForm.parse(value, default: @sorting.default)

          # update attribute based on normalized value
          super(@sorting.to_param)
        end

        class Sort # :nodoc:
          include Backend

          def initialize(app)
            @app = app
          end

          def call(collection)
            @collection                            = @app.call(collection)
            @collection.sorting, @collection.items = @collection.sorting.apply(@collection.items) if @collection.sorting
            @collection
          end

          # pagy shim
          def params
            @collection.attributes
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
katalyst-tables-3.0.0.beta1 app/models/concerns/katalyst/tables/collection/sorting.rb