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.



91
92
93
94
95
# File 'lib/t_ruby/constraint_checker.rb', line 91

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.



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

def base_type
  @base_type
end

#patternObject (readonly)

Returns the value of attribute pattern.



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

def pattern
  @pattern
end

Instance Method Details

#satisfied?(value) ⇒ Boolean

Returns:

  • (Boolean)


97
98
99
100
101
# File 'lib/t_ruby/constraint_checker.rb', line 97

def satisfied?(value)
  return false unless value.is_a?(String)

  @pattern.match?(value)
end

#validation_code(var_name) ⇒ Object



103
104
105
# File 'lib/t_ruby/constraint_checker.rb', line 103

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