Class: MarkovWords::FileStore

Inherits:
Object
  • Object
show all
Defined in:
lib/markov_words/file_store.rb

Overview

Utility for persisting arbitrary data to disk.

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ FileStore

Returns a new instance of FileStore.

Parameters:

  • opts (Hash)

    a customizable set of options

Options Hash (opts):

  • :file_path (String)

    Path and name for where the file should be stored.

  • :flush_data (Boolean)

    Do you want the file to be cleared on open?



13
14
15
16
17
# File 'lib/markov_words/file_store.rb', line 13

def initialize(opts)
  @file_path = opts.fetch :file_path, "/tmp/#{SecureRandom.base64}"
  initialize_db
  empty_db if opts[:flush_data]
end

Instance Method Details

#retrieve_data(key = '') ⇒ Object

Retrieve whatever data is stored in at key, and return it!



34
35
36
37
38
# File 'lib/markov_words/file_store.rb', line 34

def retrieve_data(key = '')
  key = key.to_s unless key.is_a? String
  data_array = @db.execute 'SELECT value FROM data WHERE key = ?', key
  Marshal.load(data_array[0][0]) unless data_array[0].nil?
end

#store_data(key = :discard, data = nil) ⇒ Object

Store arbitary data, named with a key

Parameters:

  • key (Symbol) (defaults to: :discard)

    Unique key for later data retrieval

  • data (Object) (defaults to: nil)

    Any Marshal-able object



22
23
24
25
26
27
28
29
30
31
# File 'lib/markov_words/file_store.rb', line 22

def store_data(key = :discard, data = nil)
  key = key.to_s unless key.is_a? String
  if data_exists(key)
    @db.execute 'UPDATE data SET value = ? WHERE key = ?',
                [Marshal.dump(data), key]
  else
    @db.execute 'INSERT INTO data VALUES ( ?, ? )',
                [key, Marshal.dump(data)]
  end
end