Class: SeeingIsBelieving::SwapFiles

Inherits:
Object
  • Object
show all
Defined in:
lib/seeing_is_believing/swap_files.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path, backup_path, user_program, rewritten_program, &block) ⇒ SwapFiles

Returns a new instance of SwapFiles.



28
29
30
31
32
33
34
# File 'lib/seeing_is_believing/swap_files.rb', line 28

def initialize(file_path, backup_path, user_program, rewritten_program, &block)
  self.file_path         = file_path
  self.block             = block
  self.backup_path       = backup_path
  self.user_program      = user_program
  self.rewritten_program = rewritten_program
end

Class Method Details

.call(*args, &block) ⇒ Object

Might honeslty make more sense to break this out into 2 different classes. We’ve got to do some confusing state accounting since there are really 2 algorithms here:

if the file exists:

make sure there isn't a backup (could cause the user to lose their file)
back the file up
write the rewritten code to the file
if we are told to show the user program
  move the backup over the top of the rewritten file
  do nothing in the ensure block
else
  in the ensure block: move the backup over the top of the rewritten file

if the file DNE:

write the rewritten code to the file
if we are told to show the user program
  write the user program to the file
delete the file in the ensure block


24
25
26
# File 'lib/seeing_is_believing/swap_files.rb', line 24

def self.call(*args, &block)
  new(*args, &block).call
end

Instance Method Details

#callObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/seeing_is_believing/swap_files.rb', line 36

def call
  HardCoreEnsure.call \
    code: -> {
      File.exist? backup_path and
        raise TempFileAlreadyExists.new(file_path, backup_path)

      @has_file = File.exist? file_path

      if @has_file
        File.rename file_path, backup_path
        @needs_restore = true
      end

      save_file rewritten_program

      block.call self
    },
    ensure: -> {
      set_back_to_initial_conditions
    }
end

#show_user_programObject



58
59
60
61
62
63
64
# File 'lib/seeing_is_believing/swap_files.rb', line 58

def show_user_program
  if @needs_restore
    restore
  else
    save_file user_program
  end
end