Class: EacRubyUtils::Configs::File

Inherits:
Object
  • Object
show all
Includes:
SimpleCache
Defined in:
lib/eac_ruby_utils/configs/file.rb

Constant Summary

Constants included from SimpleCache

SimpleCache::UNCACHED_METHOD_PATTERN

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from SimpleCache

#method_missing, #reset_cache, #respond_to_missing?

Constructor Details

#initialize(path, options = {}) ⇒ File

Valid options: [:autosave]



17
18
19
20
21
# File 'lib/eac_ruby_utils/configs/file.rb', line 17

def initialize(path, options = {})
  @path = path
  @options = options.to_sym_keys_hash.freeze
  load
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class EacRubyUtils::SimpleCache

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



14
15
16
# File 'lib/eac_ruby_utils/configs/file.rb', line 14

def options
  @options
end

#pathObject (readonly)

Returns the value of attribute path.



14
15
16
# File 'lib/eac_ruby_utils/configs/file.rb', line 14

def path
  @path
end

Instance Method Details

#[](entry_key) ⇒ Object



49
50
51
# File 'lib/eac_ruby_utils/configs/file.rb', line 49

def [](entry_key)
  read(entry_key)
end

#[]=(entry_key, entry_value) ⇒ Object



40
41
42
# File 'lib/eac_ruby_utils/configs/file.rb', line 40

def []=(entry_key, entry_value)
  write(entry_key, entry_value)
end

#autosave?Boolean

Returns:



57
58
59
# File 'lib/eac_ruby_utils/configs/file.rb', line 57

def autosave?
  options[:autosave] ? true : false
end

#clearObject



23
24
25
# File 'lib/eac_ruby_utils/configs/file.rb', line 23

def clear
  self.data = ::EacRubyUtils::PathsHash.new({})
end

#loadObject



32
33
34
35
36
37
38
# File 'lib/eac_ruby_utils/configs/file.rb', line 32

def load
  self.data = if ::File.exist?(path) && ::File.size(path).positive?
                ::EacRubyUtils::PathsHash.new(YAML.load_file(path))
              else
                {}
              end
end

#read(entry_key) ⇒ Object



53
54
55
# File 'lib/eac_ruby_utils/configs/file.rb', line 53

def read(entry_key)
  data[entry_key]
end

#saveObject



27
28
29
30
# File 'lib/eac_ruby_utils/configs/file.rb', line 27

def save
  ::FileUtils.mkdir_p(::File.dirname(path))
  ::File.write(path, data.to_h.to_yaml)
end

#write(entry_key, entry_value) ⇒ Object



44
45
46
47
# File 'lib/eac_ruby_utils/configs/file.rb', line 44

def write(entry_key, entry_value)
  data[entry_key] = entry_value
  save if autosave?
end