Class: Reflekt::ArrayRule

Inherits:
Rule
  • Object
show all
Defined in:
lib/rules/array_rule.rb

Instance Attribute Summary

Attributes inherited from Rule

#type

Instance Method Summary collapse

Constructor Details

#initializeArrayRule

Returns a new instance of ArrayRule.



6
7
8
9
10
11
12
# File 'lib/rules/array_rule.rb', line 6

def initialize()
  @type = :array
  @min = nil
  @max = nil
  @min_length = nil
  @max_length = nil
end

Instance Method Details

#randomObject



83
84
85
86
87
88
89
90
91
# File 'lib/rules/array_rule.rb', line 83

def random()
  array = Array.new(rand(@min_length..@max_length))

  array.each_with_index do |item, index|
    array[index] = rand(@min..@max)
  end

  return array
end

#resultObject



73
74
75
76
77
78
79
80
81
# File 'lib/rules/array_rule.rb', line 73

def result()
  {
    :type => @type,
    :min => @min,
    :max => @max,
    :min_length => @min_length,
    :max_length => @max_length
  }
end

#test(value) ⇒ Object

Parameters:

  • value (Array)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rules/array_rule.rb', line 54

def test(value)
  # Handle empty value.
  return true if value.empty? && @min_length == 0 && @max_length == 0

  unless value.empty?
    # Numbers only; if the value is a string then there will be no min/max.
    unless @min.nil? || @max.nil?
      return false if value.min() < @min
      return false if value.max() > @max
    end

    # Min/max length.
    return false if value.length < @min_length
    return false if value.length > @max_length
  end

  true
end

#train(meta) ⇒ Object

Parameters:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rules/array_rule.rb', line 17

def train(meta)
  if Meta.numeric? meta[:min]
    # Min value.
    meta_min = meta[:min].to_i
    if @min.nil?
      @min = meta_min
    else
      @min = meta_min if meta_min < @min
    end

    # Max value.
    meta_max = meta[:max].to_i
    if @max.nil?
      @max = meta_max
    else
      @max = meta_max if meta_max > @max
    end
  end

  # Min length.
  if @min_length.nil?
    @min_length = meta[:length]
  else
    @min_length = meta[:length] if meta[:length] < @min_length
  end

  # Max length.
  if @max_length.nil?
    @max_length = meta[:length]
  else
    @max_length = meta[:length] if meta[:length] > @max_length
  end
end