Class: Contracts::Constraints::Length

Inherits:
Base
  • Object
show all
Defined in:
lib/contracts.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min: nil, max: nil, exactly: nil) ⇒ Length

Returns a new instance of Length.

Raises:



295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/contracts.rb', line 295

def initialize(min: nil, max: nil, exactly: nil)
  if exactly
    raise DefinitionError, "length exactly cannot be combined with min or max" unless min.nil? && max.nil?

    @min = @max = Integer(exactly)
  else
    @min = min && Integer(min)
    @max = max && Integer(max)
  end
  raise DefinitionError, "length requires min, max, or exactly" if @min.nil? && @max.nil?
  raise DefinitionError, "length min cannot exceed max" if @min && @max && @min > @max
end

Instance Attribute Details

#maxObject (readonly)

Returns the value of attribute max.



293
294
295
# File 'lib/contracts.rb', line 293

def max
  @max
end

#minObject (readonly)

Returns the value of attribute min.



293
294
295
# File 'lib/contracts.rb', line 293

def min
  @min
end

Instance Method Details

#descriptionObject



317
318
319
320
321
322
323
# File 'lib/contracts.rb', line 317

def description
  return "length #{min}" if min && max && min == max
  return "length >= #{min}" if min && max.nil?
  return "length <= #{max}" if max && min.nil?

  "length #{min}..#{max}"
end

#matches?(value) ⇒ Boolean

Returns:

  • (Boolean)


308
309
310
311
312
313
314
315
# File 'lib/contracts.rb', line 308

def matches?(value)
  size = length_of(value)
  return false unless size
  return false if min && size < min
  return false if max && size > max

  true
end

#to_hObject



325
# File 'lib/contracts.rb', line 325

def to_h = super.merge(min: min, max: max)