Class: Reflekt::StringRule

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

Instance Attribute Summary collapse

Attributes inherited from Rule

#type

Instance Method Summary collapse

Constructor Details

#initializeStringRule

Returns a new instance of StringRule.



9
10
11
12
13
# File 'lib/rules/string_rule.rb', line 9

def initialize()
  @type = :string
  @min_length = nil
  @max_length = nil
end

Instance Attribute Details

#max_lengthObject

Returns the value of attribute max_length.



7
8
9
# File 'lib/rules/string_rule.rb', line 7

def max_length
  @max_length
end

#min_lengthObject

Returns the value of attribute min_length.



6
7
8
# File 'lib/rules/string_rule.rb', line 6

def min_length
  @min_length
end

Instance Method Details

#randomObject



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

def random()
  # Pour alphabet soup.
  alpha_numeric = Array('A'..'Z') + Array('a'..'z')
  10.times do
    alpha_numeric << ' '
  end

  # Dip ladle into alphabet soup.
  last_char = nil
  sentence = Array.new(rand(@min_length..@max_length)) do |index|
    char = alpha_numeric.sample
    # Put no character next to the same character twice.
    while char == last_char
      char = alpha_numeric.sample
    end
    last_char = char
  end

  return sentence.join
end

#resultObject



45
46
47
48
49
50
51
# File 'lib/rules/string_rule.rb', line 45

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

#test(value) ⇒ Object

Parameters:

  • value (String)


37
38
39
40
41
42
43
# File 'lib/rules/string_rule.rb', line 37

def test(value)
  length = value.length

  return false if length < @min_length
  return false if length > @max_length
  true
end

#train(meta) ⇒ Object

Parameters:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rules/string_rule.rb', line 18

def train(meta)
  length = meta[:length]

  if @min_length.nil?
    @min_length = length
  else
    @min_length = length if length < @min_length
  end

  if @max_length.nil?
    @max_length = length
  else
    @max_length = length if length > @max_length
  end
end