Module: Storage::FileStore

Extended by:
FileStore
Included in:
FileStore
Defined in:
lib/banned_words/storage.rb

Instance Method Summary collapse

Instance Method Details

#empty_storageObject Also known as: new_storage

Clear the storage.



66
67
68
# File 'lib/banned_words/storage.rb', line 66

def empty_storage
  write_to_storage
end

#empty_storage!Object

Clear storage file if it exists. Otherwise an error is raised.



75
76
77
78
79
80
81
# File 'lib/banned_words/storage.rb', line 75

def empty_storage!
  if storage_exists?
    empty_storage
  else
    raise IOError, "No banned words file!"
  end
end

#ensure_storage_fileObject

Creates the storage file if it’s not present



86
87
88
# File 'lib/banned_words/storage.rb', line 86

def ensure_storage_file
  new_storage if !storage_exists?
end

#file_pathObject

Retruns the path to where the banned words file source is/should be located.



8
9
10
# File 'lib/banned_words/storage.rb', line 8

def file_path
  "#{Rails.root}/lib/banned_words.yml"
end

#list_contentsObject

Returns an array containing the banned words. If no banned words are present the returned array is empty.



46
47
48
49
# File 'lib/banned_words/storage.rb', line 46

def list_contents
  list = load_storage
  list.is_a?(Hash) ? list.keys.sort : [list]
end

#list_contents!Object

Returns an array containing the banned words if the storage file exists. Otherwise an error is raised.



55
56
57
58
59
60
61
# File 'lib/banned_words/storage.rb', line 55

def list_contents!
  if storage_exists?
    list_contents
  else
    raise IOError, "No banned words file!"
  end
end

#load_storageObject

Returns a hash containing the banned words along with their regexes. If no banned words are present the returned hash is empty.



38
39
40
# File 'lib/banned_words/storage.rb', line 38

def load_storage
  YAML.load_file(file_path) || {}
end

#remove_storage_fileObject

Mostly used in specs



93
94
95
# File 'lib/banned_words/storage.rb', line 93

def remove_storage_file
  FileUtils.rm(file_path)
end

#storage_exists?Boolean

Returns true if the banned_words.yml file exisits, false otherwise

Returns:

  • (Boolean)


15
16
17
# File 'lib/banned_words/storage.rb', line 15

def storage_exists?
  File.exists?(file_path)
end

#write_to_storage(value = nil) ⇒ Object

Write new data to storage. The supplied hash value will overwrite the exising data from the storage.

Parameters

value<Hash>

Ex: => “bw_regex_1”, :banned_word_2 => “bw_regex_2”



28
29
30
31
32
# File 'lib/banned_words/storage.rb', line 28

def write_to_storage(value = nil)
  File.open(file_path, "w+") do |file|
    YAML.dump(value, file)
  end
end