Sha256: 2378c8a1db8d1f13b92bd258cabf74bf664adc364e5cd28ef4f8b80a9d6f0a62

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require "forwardable"

module Filternator
  class ApplyFilter
    extend Forwardable

    attr_reader :filterer, :params

    def initialize(filterer, params)
      @filterer = filterer
      @params = params
    end

    def_delegators :filterer, :scope_name, :scope, :all_filters, :presenter, :default_filter

    def as_json(*args)
      {
        scope_name => presenters.as_json(*args),
        :meta => {
          :filters        => all_filters,
          :applied_filter => filter,
          :pagination     => pagination.as_json,
        },
      }
    end

    def count
      filtered_scope.count
    end

    def presenters
      paginated_scope.map(&presenter)
    end

    def pagination
      Pagination.new(paginated_scope)
    end

    def paginated_scope
      filtered_scope.paginate(page: params[:page].presence)
    end

    def filter
      params[:filter].presence || default_filter
    end

    def filtered_scope
      if valid_filter?
        # ignore 'all' on relations
        if scope.is_a?(::ActiveRecord::Relation) && filter.to_s == "all"
          scope
        else
          scope.public_send(filter)
        end
      else
        scope
      end
    end

    def valid_filter?
      filter.present? && all_filters.include?(filter)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
filternator-0.0.5 lib/filternator/apply_filter.rb