Class: TRuby::LengthConstraint

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

Overview

Length constraint for strings/arrays: Type where length condition

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:, min_length: nil, max_length: nil, exact_length: nil) ⇒ LengthConstraint



138
139
140
141
142
143
144
# File 'lib/t_ruby/constraint_checker.rb', line 138

def initialize(base_type:, min_length: nil, max_length: nil, exact_length: nil)
  @base_type = base_type
  @min_length = min_length
  @max_length = max_length
  @exact_length = exact_length
  super(type: :length, condition: build_condition)
end

Instance Attribute Details

#base_typeObject (readonly)

Returns the value of attribute base_type.



136
137
138
# File 'lib/t_ruby/constraint_checker.rb', line 136

def base_type
  @base_type
end

#exact_lengthObject (readonly)

Returns the value of attribute exact_length.



136
137
138
# File 'lib/t_ruby/constraint_checker.rb', line 136

def exact_length
  @exact_length
end

#max_lengthObject (readonly)

Returns the value of attribute max_length.



136
137
138
# File 'lib/t_ruby/constraint_checker.rb', line 136

def max_length
  @max_length
end

#min_lengthObject (readonly)

Returns the value of attribute min_length.



136
137
138
# File 'lib/t_ruby/constraint_checker.rb', line 136

def min_length
  @min_length
end

Instance Method Details

#satisfied?(value) ⇒ Boolean



146
147
148
149
150
151
152
153
# File 'lib/t_ruby/constraint_checker.rb', line 146

def satisfied?(value)
  return false unless value.respond_to?(:length)
  len = value.length
  return len == @exact_length if @exact_length
  return false if @min_length && len < @min_length
  return false if @max_length && len > @max_length
  true
end

#validation_code(var_name) ⇒ Object



155
156
157
158
159
160
161
162
163
164
# File 'lib/t_ruby/constraint_checker.rb', line 155

def validation_code(var_name)
  conditions = []
  if @exact_length
    conditions << "#{var_name}.length == #{@exact_length}"
  else
    conditions << "#{var_name}.length >= #{@min_length}" if @min_length
    conditions << "#{var_name}.length <= #{@max_length}" if @max_length
  end
  conditions.join(" && ")
end