Class: Attributor::Integer

Inherits:
Numeric
  • Object
show all
Defined in:
lib/attributor/types/integer.rb

Constant Summary collapse

EXAMPLE_RANGE =
1000.freeze

Class Method Summary collapse

Methods inherited from Numeric

family

Methods included from Type

included

Class Method Details

.example(context = nil, options: {}) ⇒ Object


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/attributor/types/integer.rb', line 14

def self.example(context=nil, options: {})
  validate_options(options)

  # Set default values
  if options[:min].nil? && options[:max].nil?
    min = 0
    max = EXAMPLE_RANGE
  elsif options[:min].nil?
    max = options[:max]
    min = max - EXAMPLE_RANGE
  elsif options[:max].nil?
    min = options[:min]
    max = min + EXAMPLE_RANGE
  else
    min = options[:min]
    max = options[:max]
  end

  # Generate random number on interval [min,max]
  rand(max-min+1) + min
end

.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **options) ⇒ Object


36
37
38
39
40
# File 'lib/attributor/types/integer.rb', line 36

def self.load(value, context=Attributor::DEFAULT_ROOT_CONTEXT, **options)
  Integer(value)
rescue TypeError
  super
end

.native_typeObject


9
10
11
# File 'lib/attributor/types/integer.rb', line 9

def self.native_type
  return ::Integer
end

.validate_options(options) ⇒ Object


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/attributor/types/integer.rb', line 42

def self.validate_options(options)
  if options.has_key?(:min) && options.has_key?(:max)
    # Both :max and :min must be integers
    raise AttributorException.new("Invalid range: [#{options[:min].inspect}, #{options[:max].inspect}]") if !options[:min].is_a?(::Integer) || !options[:max].is_a?(::Integer)

    # :max cannot be less than :min
    raise AttributorException.new("Invalid range: [#{options[:min].inspect}, #{options[:max].inspect}]") if options[:max] < options[:min]
  elsif !options.has_key?(:min) && options.has_key?(:max)
    # :max must be an integer
    raise AttributorException.new("Invalid range: [, #{options[:max].inspect}]") if !options[:max].is_a?(::Integer)
  elsif options.has_key?(:min) && !options.has_key?(:max)
    # :min must be an integer
    raise AttributorException.new("Invalid range: [#{options[:min].inspect},]") if !options[:min].is_a?(::Integer)
  else
    # Neither :min nor :max were given, noop
  end
  true
end