Class: Pact::Generator::RandomDecimal

Inherits:
Object
  • Object
show all
Defined in:
lib/pact/generator/random_decimal.rb

Overview

RandomDecimal provides the random decimal generator which will generate a decimal value of digits length

Instance Method Summary collapse

Instance Method Details

#call(hash, _params = nil, _example_value = nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pact/generator/random_decimal.rb', line 11

def call(hash, _params = nil, _example_value = nil)
  digits = hash['digits'] || 6

  raise 'RandomDecimalGenerator digits must be > 0, got $digits' if digits < 1

  return rand(0..9) if digits == 1

  return rand(0..9) + rand(1..9) / 10 if digits == 2

  pos = rand(1..digits - 1)
  precision = digits - pos
  integers = ''
  decimals = ''
  while pos.positive?
    integers += String(rand(1..9))
    pos -= 1
  end
  while precision.positive?
    decimals += String(rand(1..9))
    precision -= 1
  end

  Float("#{integers}.#{decimals}")
end

#can_generate?(hash) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/pact/generator/random_decimal.rb', line 7

def can_generate?(hash)
  hash.key?('type') && hash['type'] == 'RandomDecimal'
end