Class: SpicyValidation::Renderer

Inherits:
Object
  • Object
show all
Defined in:
lib/spicy_validation/renderer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_name:) ⇒ Renderer

Returns a new instance of Renderer.



10
11
12
# File 'lib/spicy_validation/renderer.rb', line 10

def initialize(table_name:)
  @table_name = table_name
end

Instance Attribute Details

#table_nameObject (readonly)

Returns the value of attribute table_name.



8
9
10
# File 'lib/spicy_validation/renderer.rb', line 8

def table_name
  @table_name
end

Class Method Details

.choose_table_nameObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/spicy_validation/renderer.rb', line 30

def self.choose_table_name
  puts "\e[33m[warning] If you generate validation, model file will be overwritten.\e[0m"
  hash_tables = Schema.table_names.map.with_index { |table, index| [index.to_s.to_sym, table] }.to_h
  p hash_tables
  while true
    print "Type a number you wanna generate validation > "
    num = $stdin.gets.chomp.to_sym
    break if hash_tables.key?(num)

    p "Type a number correctly!"
  end

  hash_tables[num]
end

.generate(dry_run: false) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/spicy_validation/renderer.rb', line 14

def self.generate(dry_run: false)
  table = choose_table_name
  object_table = new(table_name: table)
  return if object_table.validations.empty?

  object_table.write! if generate?(dry_run: dry_run)
end

.generate?(dry_run:) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/spicy_validation/renderer.rb', line 26

def self.generate?(dry_run:)
  !dry_run
end

Instance Method Details

#contentObject



49
50
51
52
53
54
55
# File 'lib/spicy_validation/renderer.rb', line 49

def content
  <<~MODEL
    class #{model_name} < ApplicationRecord
      #{validations.join("\n  ")}
    end
  MODEL
end

#model_nameObject



57
58
59
# File 'lib/spicy_validation/renderer.rb', line 57

def model_name
  table_name.classify
end

#validationsObject



45
46
47
# File 'lib/spicy_validation/renderer.rb', line 45

def validations
  normal_validations + unique_validations
end

#write!Object



22
23
24
# File 'lib/spicy_validation/renderer.rb', line 22

def write!
  File.write(model_path, content)
end