class Accessory::Accessors::FilterAccessor

Traverses the elements of an Enumerable that return a truthy value from a passed-in predicate block.

Aliases

Equivalents in Elixir's {hexdocs.pm/elixir/Access.html Access} module

Default constructor used by predecessor accessor

Public Class Methods

new(pred = nil, default: nil, &pred_blk) click to toggle source

Returns a new instance of {FilterAccessor}.

The predicate function may be passed in as either a positional argument, or a block.

@param pred [Proc] The predicate function to use, as an object @param pred_blk [Proc] The predicate function to use, as a block @param default [Object] the default to use if the predecessor accessor passes nil data

# File lib/accessory/accessors/filter_accessor.rb, line 27
def initialize(pred = nil, default: nil, &pred_blk)
  @pred = blk || pred
end

Public Instance Methods

ensure_valid(traversal_result) click to toggle source

@!visibility private

# File lib/accessory/accessors/filter_accessor.rb, line 37
def ensure_valid(traversal_result)
  if traversal_result.kind_of?(Enumerable)
    traversal_result
  else
    []
  end
end
get(data, &succ) click to toggle source

Feeds each element of data matching the predicate down the accessor chain, returning the results. @param data [Enumerable] the Enumerable to iterate through @return [Array] the values derived from the rest of the accessor chain

# File lib/accessory/accessors/filter_accessor.rb, line 49
def get(data, &succ)
  if succ
    (data || []).filter(&@pred).map(&succ)
  else
    data
  end
end
get_and_update(data) { |pos| ... } click to toggle source

Feeds each element of data matching the predicate down the accessor chain, overwriting data with the results.

If :pop is returned from the accessor chain, the element is dropped from the new data.

@param data [Enumerable] the Enumerable to iterate through @return [Array] a two-element array containing 1. the original values found during iteration; and 2. the new data

# File lib/accessory/accessors/filter_accessor.rb, line 65
def get_and_update(data)
  results = []
  new_data = []
  dirty = false

  (data || []).each do |pos|
    unless @pred.call(pos)
      new_data.push(pos)
      next
    end

    case yield(pos)
    in [:clean, result, _]
      results.push(result)
      new_data.push(pos)
    in [:dirty, result, new_value]
      results.push(result)
      new_data.push(new_value)
      dirty = true
    in :pop
      results.push(pos)
      dirty = true
    end
  end

  if dirty
    [:dirty, results, new_data]
  else
    [:clean, results, data]
  end
end
inspect_args() click to toggle source

@!visibility private

# File lib/accessory/accessors/filter_accessor.rb, line 32
def inspect_args
  @pred.inspect
end