Class: TRuby::PatternConstraint

Inherits:
Constraint show all
Defined in:
lib/t_ruby/constraint_checker.rb

Overview

Pattern constraint for strings: String where /pattern/

Instance Attribute Summary collapse

Attributes inherited from Constraint

#condition, #message, #type

Instance Method Summary collapse

Methods inherited from Constraint

#to_s

Constructor Details

#initialize(base_type:, pattern:) ⇒ PatternConstraint

Returns a new instance of PatternConstraint.



89
90
91
92
93
# File 'lib/t_ruby/constraint_checker.rb', line 89

def initialize(base_type:, pattern:)
  @base_type = base_type
  @pattern = pattern.is_a?(Regexp) ? pattern : Regexp.new(pattern)
  super(type: :pattern, condition: "=~ #{@pattern.inspect}")
end

Instance Attribute Details

#base_typeObject (readonly)

Returns the value of attribute base_type.



87
88
89
# File 'lib/t_ruby/constraint_checker.rb', line 87

def base_type
  @base_type
end

#patternObject (readonly)

Returns the value of attribute pattern.



87
88
89
# File 'lib/t_ruby/constraint_checker.rb', line 87

def pattern
  @pattern
end

Instance Method Details

#satisfied?(value) ⇒ Boolean

Returns:



95
96
97
98
# File 'lib/t_ruby/constraint_checker.rb', line 95

def satisfied?(value)
  return false unless value.is_a?(String)
  @pattern.match?(value)
end

#validation_code(var_name) ⇒ Object



100
101
102
# File 'lib/t_ruby/constraint_checker.rb', line 100

def validation_code(var_name)
  "#{@pattern.inspect}.match?(#{var_name})"
end