Class: Buff::Config::JSON

Inherits:
Base
  • Object
show all
Defined in:
lib/buff/config/json.rb

Instance Attribute Summary

Attributes inherited from Base

#path

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize, #to_hash

Constructor Details

This class inherits a constructor from Buff::Config::Base

Class Method Details

.from_file(path) ⇒ Buff::Config::JSON

Parameters:

  • path (String)

Returns:

Raises:


27
28
29
30
31
32
33
# File 'lib/buff/config/json.rb', line 27

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 Errors::ConfigNotFound, "No configuration found at: '#{path}'"
end

.from_hash(hash) ⇒ Buff::Config::JSON

Parameters:

  • hash (Hash)

Returns:


18
19
20
# File 'lib/buff/config/json.rb', line 18

def from_hash(hash)
  new.from_hash(hash)
end

.from_json(data) ⇒ Buff::Config::JSON

Parameters:

  • data (String)

Returns:


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

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

Instance Method Details

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

Returns:

Raises:

See Also:

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

41
42
43
44
45
# File 'lib/buff/config/json.rb', line 41

def from_json(*args)
  super
rescue ::JSON::ParserError => ex
  raise Errors::InvalidConfig, ex
end

#reloadBuff::Config::JSON

Reload the current configuration file from disk

Returns:


61
62
63
64
# File 'lib/buff/config/json.rb', line 61

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

#save(destination = self.path) ⇒ Object


47
48
49
50
51
52
53
54
55
56
# File 'lib/buff/config/json.rb', line 47

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(::JSON.pretty_generate(self.to_hash))
  end
end