Sha256: 8894fe5c601fe2c2e432232368ac18a84569c09f3fcc120abb339562d8a44950

Contents?: true

Size: 1.85 KB

Versions: 12

Compression:

Stored size: 1.85 KB

Contents


module Attributor
  class Integer
    include Attributor::Numeric

    EXAMPLE_RANGE = 1000

    def self.native_type
      ::Integer
    end

    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

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

    def self.validate_options(options)
      if options.key?(:min) && options.key?(:max)
        # Both :max and :min must be integers
        raise AttributorException, "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, "Invalid range: [#{options[:min].inspect}, #{options[:max].inspect}]" if options[:max] < options[:min]
      elsif !options.key?(:min) && options.key?(:max)
        # :max must be an integer
        raise AttributorException, "Invalid range: [, #{options[:max].inspect}]" unless options[:max].is_a?(::Integer)
      elsif options.key?(:min) && !options.key?(:max)
        # :min must be an integer
        raise AttributorException, "Invalid range: [#{options[:min].inspect},]" unless options[:min].is_a?(::Integer)
        # Neither :min nor :max were given, noop
      end
      true
    end

    def self.json_schema_type
      :integer
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
attributor-8.0 lib/attributor/types/integer.rb
attributor-7.1 lib/attributor/types/integer.rb
attributor-7.0 lib/attributor/types/integer.rb
attributor-6.5 lib/attributor/types/integer.rb
attributor-6.4 lib/attributor/types/integer.rb
attributor-6.3 lib/attributor/types/integer.rb
attributor-6.2 lib/attributor/types/integer.rb
attributor-6.1 lib/attributor/types/integer.rb
attributor-6.0 lib/attributor/types/integer.rb
attributor-5.7 lib/attributor/types/integer.rb
attributor-5.6 lib/attributor/types/integer.rb
attributor-5.5 lib/attributor/types/integer.rb