Module: RRRSpec::Server::LogFilePersister::ClassMethods

Defined in:
lib/rrrspec/server/log_file_persister.rb

Instance Method Summary collapse

Instance Method Details

#save_as_file(name, suffix: nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rrrspec/server/log_file_persister.rb', line 25

def save_as_file(name, suffix: nil)
  suffix = "_#{suffix}" if suffix
  instance_variable_set("@#{name}_dirty", false)
  define_method("#{name}_log_path") do
    return nil unless send(:key)
    File.join(
      RRRSpec.configuration.execute_log_text_path,
      "#{send(:key).gsub(/\//, '_').gsub(/:/, '/')}#{suffix}.log"
    )
  end

  define_method(name) do
    contents = instance_variable_get("@#{name}")
    if !contents
      log_path = send("#{name}_log_path")
      if log_path
        contents = File.exist?(log_path) ?  File.read(log_path) : nil
        instance_variable_set("@#{name}", contents) if contents
      end
    end
    contents
  end

  define_method("#{name}=") do |val|
    if send(name) != val
      instance_variable_set("@#{name}_dirty", true)
      instance_variable_set("@#{name}", val)
    end
  end

  after_save do
    if instance_variable_get("@#{name}")
      log_path = send("#{name}_log_path")
      FileUtils.mkdir_p(File.dirname(log_path))
      File.open(log_path, 'w') { |fp| fp.write(send(name)) }
    end
  end
end