Class: AnnotateModel::Annotator

Inherits:
Object
  • Object
show all
Defined in:
lib/annotate_model/annotator.rb

Class Method Summary collapse

Class Method Details

.annotate(model_names) ⇒ Object



3
4
5
6
7
# File 'lib/annotate_model/annotator.rb', line 3

def self.annotate(model_names)
  process_files(AnnotateModel::Finder.model_files!(model_names))
rescue ModelFileNotFoundError => e
  warn e.message
end

.annotate_allObject



9
10
11
# File 'lib/annotate_model/annotator.rb', line 9

def self.annotate_all
  process_files(AnnotateModel::Finder.all_model_files)
end

.annotate_file(file) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/annotate_model/annotator.rb', line 30

def self.annotate_file(file)
  return :skipped unless AnnotationDecider.new(file).annotate?

  schema_info = fetch_schema_info(file)
  return :failed unless schema_info

  content = File.read(file.to_s)
  content = remove_existing_annotation(content)
  annotated_content = <<~ANNOTATION + content
    # == Schema Information
    #
    #{schema_info}
    # ==
  ANNOTATION

  File.write(file.to_s, annotated_content)
  :run
end

.fetch_schema_info(file) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/annotate_model/annotator.rb', line 53

def self.fetch_schema_info(file)
  begin
    columns = ActiveRecord::Base.connection.columns(file.table_name)
  rescue ActiveRecord::StatementInvalid
    warn "Could not find table '#{file.table_name}'"
    return
  end

  columns.map do |column|
    "# #{column.name.ljust(10)} :#{column.type}#{' ' * (15 - column.type.to_s.length)}#{column.null ? '' : ' not null'}"
  end.join("\n")
end

.log_results(run_files, failed_files) ⇒ Object



66
67
68
69
70
71
72
73
# File 'lib/annotate_model/annotator.rb', line 66

def self.log_results(run_files, failed_files)
  puts "Annotated files:"
  run_files.each { |file| puts "  - #{file.relative_path}" }

  puts "Failed files:"
  failed_files.each { |file| puts "  - #{file.relative_path}" }
  puts "#{run_files.size} runs, #{failed_files.size} failures"
end

.process_files(files) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/annotate_model/annotator.rb', line 13

def self.process_files(files)
  run_files = []
  failed_files = []

  files.each do |file|
    result = annotate_file(file)
    case result
    when :run
      run_files << file
    when :failed
      failed_files << file
    end
  end

  log_results(run_files, failed_files)
end

.remove_existing_annotation(content) ⇒ Object



49
50
51
# File 'lib/annotate_model/annotator.rb', line 49

def self.remove_existing_annotation(content)
  content.sub(/^# == Schema Information\n(#.*\n)*# ==\n/m, '')
end