Class: TRuby::LengthConstraint
- Inherits:
-
Constraint
- Object
- Constraint
- TRuby::LengthConstraint
- Defined in:
- lib/t_ruby/constraint_checker.rb
Overview
Length constraint for strings/arrays: Type where length condition
Instance Attribute Summary collapse
-
#base_type ⇒ Object
readonly
Returns the value of attribute base_type.
-
#exact_length ⇒ Object
readonly
Returns the value of attribute exact_length.
-
#max_length ⇒ Object
readonly
Returns the value of attribute max_length.
-
#min_length ⇒ Object
readonly
Returns the value of attribute min_length.
Attributes inherited from Constraint
Instance Method Summary collapse
-
#initialize(base_type:, min_length: nil, max_length: nil, exact_length: nil) ⇒ LengthConstraint
constructor
A new instance of LengthConstraint.
- #satisfied?(value) ⇒ Boolean
- #validation_code(var_name) ⇒ Object
Methods inherited from Constraint
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_type ⇒ Object (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_length ⇒ Object (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_length ⇒ Object (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_length ⇒ Object (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 |