Class: Configural::Config::JSONFile

Inherits:
FileBase
  • Object
show all
Defined in:
lib/configural/config/json_file.rb

Overview

Implementation of FileBase using JSON for serialization.

You must have the ‘json’ library installed to use this format. This library comes standard with some versions of Ruby. Otherwise, install the ‘json’ gem.

Instance Attribute Summary

Attributes inherited from FileBase

#path

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from FileBase

#[], #[]=, #clear, #close, #delete, #each, #exists?, get_format_by_extname, get_format_by_name, inherited, #keys, #load, #load!, #save, #save!, #to_hash

Constructor Details

#initialize(*args) ⇒ JSONFile

Returns a new instance of JSONFile.



49
50
51
52
# File 'lib/configural/config/json_file.rb', line 49

def initialize(*args)
  require 'json'
  super
end

Class Method Details

.extnamesObject



44
45
46
# File 'lib/configural/config/json_file.rb', line 44

def self.extnames
  ['.json']
end

.formatObject



40
41
42
# File 'lib/configural/config/json_file.rb', line 40

def self.format
  'json'
end

Instance Method Details

#_loadObject



54
55
56
57
58
59
60
61
62
63
# File 'lib/configural/config/json_file.rb', line 54

def _load
  @data = File.open(path, 'r'){|f| JSON.load(f) }
  @data ||= {}
rescue Errno::ENOENT
  @data = {}
rescue JSON::ParserError, Errno::EACCESS => e
  warn( "WARNING: Could not load config file #{path.inspect}:\n" +
        e.inspect + "\nUsing empty dataset instead." )
  @data = {}
end

#_saveObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/configural/config/json_file.rb', line 65

def _save
  require 'fileutils'
  FileUtils.mkdir_p( File.dirname(path) )
  File.open(path,'w'){ |f|
    f.write( JSON.pretty_generate(@data) )
  }
rescue JSON::GeneratorError, Errno::EACCESS => e
  warn( "WARNING: Could not save config file #{path.inspect}:\n" +
        e.inspect )
end