class Compose::HandleExit

Constants

MERGE
REWRITE

Public Class Methods

new(command_context) click to toggle source
# File lib/wordword/interactors/compose/handle_exit.rb, line 16
def initialize(command_context)
  @command_context = command_context
end

Public Instance Methods

call(words) click to toggle source
# File lib/wordword/interactors/compose/handle_exit.rb, line 20
def call(words)
  return unless words.any?
  return unless prompt.yes?("Save the file?")

  filename = prompt.ask("What is the filename?")
  if File.exist?(filename)
    file_mode = ask_file_mode
    if file_mode == REWRITE
      write_words(filename, words)
    elsif file_mode == MERGE
      existing_words = ReadWordTable.new.call(filename: filename).value!
      merged_words = existing_words.merge(words)

      write_words(filename, merged_words)
    end
  else
    write_words(filename, words)
  end
end

Private Instance Methods

ask_file_mode() click to toggle source
# File lib/wordword/interactors/compose/handle_exit.rb, line 42
def ask_file_mode
  prompt.select(
    "File with that name already exists. Merge, rewrite or discard current input?(it will be lost in that case)",
  ) do |menu|
    menu.choice "Merge", -> { MERGE }
    menu.choice "Rewrite", -> { REWRITE }
    menu.choice "Discard"
  end
end
write_words(filename, words) click to toggle source
# File lib/wordword/interactors/compose/handle_exit.rb, line 52
def write_words(filename, words)
  File.write(
    filename,
    words.sort.to_h.map { |word| word.join(" # ") }.join("\n"),
  )
end