Class: Docit::Ai::DocWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/docit/ai/doc_writer.rb

Instance Method Summary collapse

Constructor Details

#initialize(controller_name:) ⇒ DocWriter

Returns a new instance of DocWriter.



9
10
11
12
# File 'lib/docit/ai/doc_writer.rb', line 9

def initialize(controller_name:)
  @controller_name = controller_name
  @module_parts = build_module_parts
end

Instance Method Details

#controller_has_use_docs?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
# File 'lib/docit/ai/doc_writer.rb', line 30

def controller_has_use_docs?
  path = controller_file_path
  return false if path && File.exist?(path) == false

  File.read(path).include?("use_docs")
end

#doc_file_pathObject



14
15
16
17
18
19
20
# File 'lib/docit/ai/doc_writer.rb', line 14

def doc_file_path
  parts = @controller_name.underscore.delete_suffix("_controller").split("/")
  filename = "#{parts.last}_docs.rb"
  dir_parts = parts[0..-2]

  File.join(Rails.root, "app", "docs", *dir_parts, filename)
end

#doc_module_nameObject



22
23
24
# File 'lib/docit/ai/doc_writer.rb', line 22

def doc_module_name
  @controller_name.delete_suffix("Controller").gsub("::", "::") + "Docs"
end

#file_exists?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/docit/ai/doc_writer.rb', line 26

def file_exists?
  File.exist?(doc_file_path)
end

#inject_use_docsObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/docit/ai/doc_writer.rb', line 37

def inject_use_docs
  path = controller_file_path
  return false if path && File.exist?(path) == false
  return false if controller_has_use_docs?

  content = File.read(path)
  class_pattern = /^(\s*class\s+\S+.*$)/
  match = content.match(class_pattern)
  return false if match.nil?

  indent = match[1][/^\s*/] + "  "
  use_docs_line = "#{indent}use_docs #{doc_module_name}\n"
  content = content.sub(class_pattern, "\\1\n#{use_docs_line}")

  File.write(path, content)
  true
end

#write(doc_blocks) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/docit/ai/doc_writer.rb', line 55

def write(doc_blocks)
  if file_exists?
    append_to_existing(doc_blocks)
  else
    create_new_file(doc_blocks)
  end
end