class DotCfg
uses JSON or YAML for serialization top-level structure is object/hash/dict
e.g. d = DotCfg.new
(‘~/.dotcfg’) d = ‘world’ d # => “world” d # => nil d.save d = “bent” d.load d # => nil
Constants
- PROCS
Attributes
filename[R]
format[R]
Public Class Methods
new(filename, format = :yaml)
click to toggle source
# File lib/dotcfg.rb, line 33 def initialize filename, format = :yaml @filename = File.expand_path filename @format = format @cfg = Hash.new File.exist?(@filename) ? self.try_load : self.reset end
Public Instance Methods
[](key)
click to toggle source
@cfg manipulation
# File lib/dotcfg.rb, line 44 def [] key @cfg[key] end
[]=(key, value)
click to toggle source
# File lib/dotcfg.rb, line 48 def []= key, value @cfg[key] = value end
delete(key)
click to toggle source
# File lib/dotcfg.rb, line 52 def delete key @cfg.delete key end
deserialize(junk)
click to toggle source
# File lib/dotcfg.rb, line 70 def deserialize junk data = self.class::PROCS.fetch(@format)[:from].call junk unless data.is_a? Hash raise ArgumentError, "invalid junk: #{junk} (#{junk.class})" end data.each { |k, v| self[k] = v } @cfg end
load()
click to toggle source
# File lib/dotcfg.rb, line 91 def load File.open(@filename, 'r') { |f| self.deserialize f.read } end
pretty()
click to toggle source
# File lib/dotcfg.rb, line 79 def pretty self.class::PROCS.fetch(@format)[:pretty].call @cfg end
reset()
click to toggle source
# File lib/dotcfg.rb, line 112 def reset @cfg = Hash.new self.save end
save()
click to toggle source
file operations
# File lib/dotcfg.rb, line 87 def save File.open(@filename, 'w') { |f| f.write self.serialize } end
serialize()
click to toggle source
serialization, using PROCS
# File lib/dotcfg.rb, line 65 def serialize raise "invalid storage" unless @cfg.is_a? Hash self.class::PROCS.fetch(@format)[:to].call @cfg end
to_h()
click to toggle source
if you need to call this, you might be Doing It Wrong (tm)
# File lib/dotcfg.rb, line 57 def to_h @cfg end
try_load()
click to toggle source
# File lib/dotcfg.rb, line 95 def try_load rescues = 0 begin self.load rescue SystemCallError, ArgumentError, JSON::ParserError => e rescues += 1 puts "#{e} (#{e.class})" if rescues < 2 puts "Resetting #{@filename}" self.reset retry end puts "try_load failed!" raise e end end