class Meshchat::Configuration::HashFile

Constants

DEFAULT_SETTINGS

Attributes

_hash[RW]

Public Class Methods

new() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 9
def initialize
  self._hash = default_settings.dup
  exists? ? load : save
end

Public Instance Methods

[](key) click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 14
def [](key)
  _hash[key.to_s]
end
[]=(key, value) click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 18
def []=(key, value)
  _hash[key.to_s] = value
end
as_hash() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 42
def as_hash
  _hash
end
default_settings() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 71
def default_settings
  @default_settings ? @default_settings : DEFAULT_SETTINGS
end
display() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 38
def display
  _hash.inspect
end
exists?() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 62
def exists?
  File.exist?(filename)
end
filename() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 66
def filename
  return @filename if @filename
  raise 'filename must be set'
end
load() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 22
def load
  f = read_file
  begin
    self._hash = JSON.parse(f)
  rescue => e
    Display.alert e.message
    self._hash = default_settings
    Display.warning 'writing defaults...'
    save
  end
end
read_file() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 34
def read_file
  File.read(filename)
end
save() click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 46
def save
  # backup
  exists = exists?
  File.rename(filename, filename + '.bak') if exists
  # write
  File.open(filename, 'w') { |f| f.syswrite(_hash.to_json) }
  # remove backup
  File.delete(filename + '.bak') if exists
end
set(key, with: value) click to toggle source
# File lib/meshchat/configuration/hash_file.rb, line 56
def set(key, with: value)
  self[key] = with
  save
  "#{key} set to #{with}"
end