Class: CodeGenerator::Generator
- Inherits:
-
Object
- Object
- CodeGenerator::Generator
- Defined in:
- lib/code_generator/generator.rb
Instance Attribute Summary collapse
-
#length ⇒ Object
Returns the value of attribute length.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#uniqueness ⇒ Object
Returns the value of attribute uniqueness.
Class Method Summary collapse
Instance Method Summary collapse
- #generate_code ⇒ Object
-
#initialize(opts = {}) ⇒ Generator
constructor
A new instance of Generator.
- #random_string ⇒ Object
- #randomized_array(&block) ⇒ Object
- #unique? ⇒ Boolean
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
#length ⇒ Object
Returns the value of attribute length.
10 11 12 |
# File 'lib/code_generator/generator.rb', line 10 def length @length end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
9 10 11 |
# File 'lib/code_generator/generator.rb', line 9 def model @model end |
#uniqueness ⇒ Object
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_code ⇒ Object
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_string ⇒ Object
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
19 20 21 |
# File 'lib/code_generator/generator.rb', line 19 def unique? @model.send(:where, {@field_name => @code}).empty? end |