Class: Meshchat::Configuration::HashFile

Inherits:
Object
  • Object
show all
Defined in:
lib/meshchat/configuration/hash_file.rb

Direct Known Subclasses

Settings

Constant Summary collapse

DEFAULT_SETTINGS =
{}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHashFile

Returns a new instance of HashFile.



9
10
11
12
# File 'lib/meshchat/configuration/hash_file.rb', line 9

def initialize
  self._hash = default_settings.dup
  exists? ? load : save
end

Instance Attribute Details

#_hashObject

Returns the value of attribute _hash.



5
6
7
# File 'lib/meshchat/configuration/hash_file.rb', line 5

def _hash
  @_hash
end

Instance Method Details

#[](key) ⇒ Object



14
15
16
# File 'lib/meshchat/configuration/hash_file.rb', line 14

def [](key)
  _hash[key.to_s]
end

#[]=(key, value) ⇒ Object



18
19
20
# File 'lib/meshchat/configuration/hash_file.rb', line 18

def []=(key, value)
  _hash[key.to_s] = value
end

#as_hashObject



42
43
44
# File 'lib/meshchat/configuration/hash_file.rb', line 42

def as_hash
  _hash
end

#default_settingsObject



71
72
73
# File 'lib/meshchat/configuration/hash_file.rb', line 71

def default_settings
  @default_settings ? @default_settings : DEFAULT_SETTINGS
end

#displayObject



38
39
40
# File 'lib/meshchat/configuration/hash_file.rb', line 38

def display
  _hash.inspect
end

#exists?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/meshchat/configuration/hash_file.rb', line 62

def exists?
  File.exist?(filename)
end

#filenameObject



66
67
68
69
# File 'lib/meshchat/configuration/hash_file.rb', line 66

def filename
  return @filename if @filename
  raise 'filename must be set'
end

#loadObject



22
23
24
25
26
27
28
29
30
31
32
# 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_fileObject



34
35
36
# File 'lib/meshchat/configuration/hash_file.rb', line 34

def read_file
  File.read(filename)
end

#saveObject



46
47
48
49
50
51
52
53
54
# 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) ⇒ Object



56
57
58
59
60
# File 'lib/meshchat/configuration/hash_file.rb', line 56

def set(key, with: value)
  self[key] = with
  save
  "#{key} set to #{with}"
end