Class: YES::Constraints::Regexp

Inherits:
NodeConstraint show all
Defined in:
lib/yes/constraints/regexp.rb

Overview

Validate matching values against a regular expression. All values are converted to strings (using #to_s) for comparison.

//pin:
  regexp: /^\d\s\d\d$/

Instance Attribute Summary

Attributes inherited from NodeConstraint

#node

Attributes inherited from AbstractConstraint

#nodes, #spec, #tree

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NodeConstraint

#initialize, #tag, #value

Methods inherited from AbstractConstraint

#applicable?, inherited, #initialize, #match_delta, #recurse_valid?, #valid?

Constructor Details

This class inherits a constructor from YES::Constraints::NodeConstraint

Class Method Details

.applicable?(spec) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/yes/constraints/regexp.rb', line 23

def self.applicable?(spec)
  spec['regexp']
end

.checklist(spec, tree, nodes) ⇒ Array<Validaiton>

Returns:

  • (Array<Validaiton>)


15
16
17
18
19
20
# File 'lib/yes/constraints/regexp.rb', line 15

def self.checklist(spec, tree, nodes)
  return [] unless applicable?(spec)
  nodes.map do |node|
    new(spec, tree, node)
  end
end

Instance Method Details

#parse_regexp(re) ⇒ Regexp

The regular expression from ‘spec`.

Returns:

  • (Regexp)

    spec’s regular expression



39
40
41
42
43
44
45
46
# File 'lib/yes/constraints/regexp.rb', line 39

def parse_regexp(re)
  case re
  when /^\/(.*?)\/(\w*)$/
    ::Regexp.new($1)  # TODO: modifiers
  else
    ::Regexp.new(re)
  end
end

#validate(spec) ⇒ Boolean

Validate matching values against a regular expression. All values are converted to strings (using #to_s) for comparison.

Returns:

  • (Boolean)

    validity



31
32
33
34
# File 'lib/yes/constraints/regexp.rb', line 31

def validate(spec)
  regexp = parse_regexp(spec['regexp'])
  regexp =~ node.value ? true : false
end