Class: CodeGenerator::Generator

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Generator

Returns a new instance of Generator.



12
13
14
15
16
17
# File 'lib/code_generator/generator.rb', line 12

def initialize(opts = {})
  opts.symbolize_keys!
  @length     = opts.delete(:length) || CodeGenerator.length
  @uniqueness = opts.delete(:uniqueness)
  set_model_and_field! if uniqueness
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



10
11
12
# File 'lib/code_generator/generator.rb', line 10

def length
  @length
end

#modelObject (readonly)

Returns the value of attribute model.



9
10
11
# File 'lib/code_generator/generator.rb', line 9

def model
  @model
end

#uniquenessObject

Returns the value of attribute uniqueness.



10
11
12
# File 'lib/code_generator/generator.rb', line 10

def uniqueness
  @uniqueness
end

Class Method Details

.generate(opts = {}) ⇒ Object



46
47
48
49
# File 'lib/code_generator/generator.rb', line 46

def generate(opts = {})
  cg = new(opts)
  cg.generate_code
end

Instance Method Details

#generate_codeObject



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

def generate_code
  @code = random_string
  if generate_unique?
    @code = random_string until(unique?)
  end
  @code
end

#random_stringObject



23
24
25
26
27
28
29
30
31
# File 'lib/code_generator/generator.rb', line 23

def random_string
  chars = CodeGenerator.valid_characters.dup
  generator = if CodeGenerator.repeat_chars
    lambda{ chars.sample() }
  else
    lambda{ chars.delete_at(rand(chars.length)) }
  end
  randomized_array &generator      
end

#randomized_array(&block) ⇒ Object



33
34
35
# File 'lib/code_generator/generator.rb', line 33

def randomized_array(&block)
  Array.new(length){ block.call }.join
end

#unique?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/code_generator/generator.rb', line 19

def unique?
  @model.send(:where, {@field_name => @code}).empty?
end