Class: Chozo::Config::JSON

Inherits:
Abstract show all
Defined in:
lib/chozo/config/json.rb

Overview

Author:

Instance Attribute Summary

Attributes inherited from Abstract

#path

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Abstract

#initialize, #to_hash

Methods included from VariaModel

#_attributes_, #errors, #from_hash, #get_attribute, included, #mass_assign, #set_attribute, #to_json, #valid?, #validate

Constructor Details

This class inherits a constructor from Chozo::Config::Abstract

Class Method Details

.from_file(path) ⇒ ~Chozo::Config::JSON

Parameters:

  • path (String)

Returns:

Raises:



20
21
22
23
24
25
26
# File 'lib/chozo/config/json.rb', line 20

def from_file(path)
  path = File.expand_path(path)
  data = File.read(path)
  new(path).from_json(data)
rescue TypeError, Errno::ENOENT, Errno::EISDIR
  raise Chozo::Errors::ConfigNotFound, "No configuration found at: '#{path}'"
end

.from_json(data) ⇒ ~Chozo::Config::JSON

Parameters:

  • data (String)

Returns:



11
12
13
# File 'lib/chozo/config/json.rb', line 11

def from_json(data)
  new.from_json(data)
end

Instance Method Details

#from_json(*args) ⇒ Chozo::Config::JSON

Returns:

Raises:

See Also:

  • Chozo::Config::JSON.{VariaModel{VariaModel#from_json}


34
35
36
37
38
# File 'lib/chozo/config/json.rb', line 34

def from_json(*args)
  super
rescue MultiJson::DecodeError => e
  raise Chozo::Errors::InvalidConfig, e
end

#reloadChozo::Config::JSON

Reload the current configuration file from disk

Returns:



54
55
56
57
# File 'lib/chozo/config/json.rb', line 54

def reload
  mass_assign(self.class.from_file(path).to_hash)
  self
end

#save(destination = self.path) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/chozo/config/json.rb', line 40

def save(destination = self.path)
  if destination.nil?
    raise Errors::ConfigSaveError, "Cannot save configuration without a destination. Provide one to save or set one on the object."
  end

  FileUtils.mkdir_p(File.dirname(destination))
  File.open(destination, 'w+') do |f|
    f.write(self.to_json(pretty: true))
  end
end