Sha256: 7eecc3b7b0ffbde6c33418e41ce4faf4557462be8ff37637db2ce1ba0ff9656b

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

require_relative 'refinements'

module Rack
  module Reducer
    # call `reduce` on a params hash, filtering data via lambdas with
    # matching keyword arguments
    class Reduction
      using Refinements # define Proc#required_argument_names, #satisfies?, etc

      def initialize(dataset, *filters)
        @dataset = dataset
        @filters = filters
      end

      # Run +@filters+ against the params argument
      # @param [Hash, ActionController::Parameters, nil] params
      #   a Rack-compatible params hash
      # @return +@dataset+ with the matching filters applied
      def apply(params)
        return @dataset if !params || params.empty?

        symbolized_params = params.to_unsafe_h.symbolize_keys
        @filters.reduce(@dataset) do |data, filter|
          next data unless filter.satisfies?(symbolized_params)

          data.instance_exec(
            **symbolized_params.slice(*filter.all_argument_names),
            &filter
          )
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rack-reducer-1.1.0 lib/rack/reducer/reduction.rb