Class: MeshChat::Config::HashFile

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

Direct Known Subclasses

Settings

Constant Summary collapse

DEFAULT_SETTINGS =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHashFile

Returns a new instance of HashFile.



8
9
10
11
# File 'lib/meshchat/config/hash_file.rb', line 8

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

Instance Attribute Details

#_hashObject

Returns the value of attribute _hash.



4
5
6
# File 'lib/meshchat/config/hash_file.rb', line 4

def _hash
  @_hash
end

Instance Method Details

#[](key) ⇒ Object



13
14
15
# File 'lib/meshchat/config/hash_file.rb', line 13

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

#[]=(key, value) ⇒ Object



17
18
19
# File 'lib/meshchat/config/hash_file.rb', line 17

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

#as_hashObject



41
42
43
# File 'lib/meshchat/config/hash_file.rb', line 41

def as_hash
  _hash
end

#default_settingsObject



70
71
72
# File 'lib/meshchat/config/hash_file.rb', line 70

def default_settings
  @default_settings ? @default_settings : DEFAULT_SETTINGS
end

#displayObject



37
38
39
# File 'lib/meshchat/config/hash_file.rb', line 37

def display
  _hash.inspect
end

#exists?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/meshchat/config/hash_file.rb', line 61

def exists?
  File.exist?(filename)
end

#filenameObject



65
66
67
68
# File 'lib/meshchat/config/hash_file.rb', line 65

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

#loadObject



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/meshchat/config/hash_file.rb', line 21

def load
  f = read_file
  begin
    self._hash = JSON.parse(f)
  rescue Exception => e
    Display.alert e.message
    self._hash = default_settings
    Display.warning 'writing defaults...'
    save
  end
end

#read_fileObject



33
34
35
# File 'lib/meshchat/config/hash_file.rb', line 33

def read_file
  File.read(filename)
end

#saveObject



45
46
47
48
49
50
51
52
53
# File 'lib/meshchat/config/hash_file.rb', line 45

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



55
56
57
58
59
# File 'lib/meshchat/config/hash_file.rb', line 55

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