Class: CFA::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/cfa/matcher.rb

Overview

Note:

The coupling to AugeasTree, AugeasElement is not a goal. Once we have more parsers it will go away.

The Matcher is used as a predicate on AugeasElement.

Being a predicate, it is passed to methods such as Enumerable#select or Array#index, returning a Boolean meaning whether a match was found.

Acting on AugeasElement means it expects a Hash ‘e` containing `e` and `e`.

It is used with the ‘&` syntax which makes the matcher act like a block/lambda/Proc (via #to_proc).

Examples:

elements = [
            {key: "#comment[]", value: "\"magical\" mostly works"},
            {key: "DRIVE",      value: "magical"},
            {key: "#comment[]", value: "'years' or 'centuries'"},
            {key: "PRECISION",  value: "years"}
           ]
drive_matcher = Matcher.new(key: "DRIVE")
i = elements.index(&drive_matcher)        # => 1

Instance Method Summary collapse

Constructor Details

#initialize(key: nil, collection: nil, value_matcher: nil) {|blk_key, blk_value| ... } ⇒ Matcher

The constructor arguments are constraints to match on an element. All constraints are optional. All supplied constraints must match, so it is a conjunction.

Parameters:

  • key (Object, nil) (defaults to: nil)

    if non-nil, constrain to elements with the name “key

  • collection (Object, nil) (defaults to: nil)

    if non-nil, constrain to elements with the name “collection[]”

  • value_matcher (Object, Regexp, nil) (defaults to: nil)

    if non-nil, constrain to elements whose value is Object or matches Regexp

Yield Parameters:

  • blk_key (Object)
  • blk_value (Object)

Yield Returns:

  • (Boolean)

    if the block is present, constrain to elements for which the block(blk_key, blk_value) returns true



40
41
42
43
44
45
46
47
48
# File 'lib/cfa/matcher.rb', line 40

def initialize(key: nil, collection: nil, value_matcher: nil, &block)
  @matcher = lambda do |element|
    return false unless key_match?(element, key)
    return false unless collection_match?(element, collection)
    return false unless value_match?(element, value_matcher)
    return false unless !block || yield(element[:key], element[:value])
    return true
  end
end

Instance Method Details

#to_procProc{AugeasElement=>Boolean}

Returns:



51
52
53
# File 'lib/cfa/matcher.rb', line 51

def to_proc
  @matcher
end