Sha256: 0363d504d46103a5df0545c3cd79366d6511989607af2e4dfaef96f1e1f874a3

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 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])
    end

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

    def filtered_scope
      if valid_filter?
        scope.public_send(filter)
      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.1 lib/filternator/apply_filter.rb