Sha256: 6a008561589c80fe4948f8033a40dc113c21dc9d71584f9ef1a1f3e6d4aa73f9

Contents?: true

Size: 1.7 KB

Versions: 4

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

# CSV Decision: CSV based Ruby decision tables.
# Created December 2017.
# @author Brett Vickers <brett@phillips-vickers.com>
# See LICENSE and README.md for details.
module CSVDecision
  # Methods to assign a matcher to data cells.
  # @api private
  class Matchers
    # Recognise numeric comparison expressions - e.g., +> 100+ or +!= 0+.
    class Numeric < Matcher
      # For example: +>= 100+ or +!= 0+.
      COMPARISON = /\A(?<comparator><=|>=|<|>|!=)\s*(?<value>\S.*)\z/
      private_constant :COMPARISON

      # Coerce the input value to a numeric representation before invoking the comparison.
      # If the coercion fails, it will produce a nil value which always fails to match.
      COMPARATORS = {
        '>'  => proc { |numeric_cell, value| Matchers.numeric(value)&.>  numeric_cell },
        '>=' => proc { |numeric_cell, value| Matchers.numeric(value)&.>= numeric_cell },
        '<'  => proc { |numeric_cell, value| Matchers.numeric(value)&.<  numeric_cell },
        '<=' => proc { |numeric_cell, value| Matchers.numeric(value)&.<= numeric_cell },
        '!=' => proc { |numeric_cell, value| Matchers.numeric(value)&.!= numeric_cell }
      }.freeze
      private_constant :COMPARATORS

      # (see Matcher#matches?)
      def self.matches?(cell)
        return false unless (match = COMPARISON.match(cell))
        return false unless (numeric_cell = Matchers.to_numeric(match['value']))

        comparator = match['comparator']
        Matchers::Proc.new(type: :proc,
                           function: COMPARATORS[comparator].curry[numeric_cell].freeze)
      end

      # (see Matcher#matches?)
      def matches?(cell)
        Numeric.matches?(cell)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
csv_decision2-0.5.1 lib/csv_decision/matchers/numeric.rb
csv_decision-0.5.1 lib/csv_decision/matchers/numeric.rb
csv_decision-0.5.0 lib/csv_decision/matchers/numeric.rb
csv_decision-0.4.1 lib/csv_decision/matchers/numeric.rb