Class: Memoria::SnapshotSaver

Inherits:
Object
  • Object
show all
Defined in:
lib/memoria/snapshot_saver.rb

Overview

Reads and writes snapshots to and from the file system.

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ SnapshotSaver

Creates a new SnapshotSaver.

Examples:

snapshot_saver = SnapshotSaver.new(Configuration.new)

Parameters:

  • configuration (Configuration)

    The gem’s configuration.



17
18
19
# File 'lib/memoria/snapshot_saver.rb', line 17

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#read(file_name) ⇒ String

Retrieves the snapshot contents for the given storage key (file name).

Examples:

When there is no snapshot for a given storage key (file name).

snapshot_saver = SnapshotSaver.new(Configuration.new)
snapshot_saver.read('/404') # => nil

When there is a snapshot for a given storage key (file name).

snapshot_saver = SnapshotSaver.new(Configuration.new)
snapshot_saver.read('index_page') # => '<h1>Hello World</h1>'

Parameters:

  • file_name (String)

    The storage key (file name) of the snapshot.

Returns:

  • (String)

    The snapshot content.



55
56
57
58
59
# File 'lib/memoria/snapshot_saver.rb', line 55

def read(file_name)
  path = absolute_path_to_file(file_name)
  return nil unless File.exist?(path)
  File.read(path)
end

#snapshot_exists?(file_name) ⇒ SnapshotSaver

Whether a snapshot for the given storage key (file name) is persisted in the file system.

Examples:

snapshot_saver = SnapshotSaver.new(Configuration.new)
snapshot_saver.snapshot_exists?(Snapshot.new('does-not')) # => false

Parameters:

  • file_name (String)

    The storage key (file name) of the snapshot.

Returns:



33
34
35
36
37
# File 'lib/memoria/snapshot_saver.rb', line 33

def snapshot_exists?(file_name)
  location = absolute_path_to_file(file_name)
  return false if location.nil?
  File.exist?(location)
end

#write(file_name, content) ⇒ Fixnum

Persists the snapshot contents for the given storage key (file name).

Examples:

snapshot_saver = SnapshotSaver.new(Configuration.new)
snapshot_saver.write('index_page', 'Homepage')
snapshot_saver.read('index_page') # => 'Homepage'

Parameters:

  • file_name (String)

    The storage key (file name) of the snapshot.

  • content (String)

    The snapshot content.

Returns:

  • (Fixnum)

    The length written.



76
77
78
79
80
81
# File 'lib/memoria/snapshot_saver.rb', line 76

def write(file_name, content)
  path = absolute_path_to_file(file_name)
  directory = File.dirname(path)
  FileUtils.mkdir_p(directory) unless File.exist?(directory)
  File.binwrite(path, content)
end