File: json.rb

package info (click to toggle)
ruby-buff-config 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 200 kB
  • sloc: ruby: 481; makefile: 4
file content (67 lines) | stat: -rw-r--r-- 1,723 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'json'
require 'buff/config'

module Buff
  module Config
    class JSON < Config::Base
      class << self
        # @param [String] data
        #
        # @return [Buff::Config::JSON]
        def from_json(data)
          new.from_json(data)
        end

        # @param [Hash] hash
        #
        # @return [Buff::Config::JSON]
        def from_hash(hash)
          new.from_hash(hash)
        end

        # @param [String] path
        #
        # @raise [Buff::Errors::ConfigNotFound]
        #
        # @return [Buff::Config::JSON]
        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
      end

      # @see {VariaModel#from_json}
      #
      # @raise [Buff::Errors::InvalidConfig]
      #
      # @return [Buff::Config::JSON]
      def from_json(*args)
        super
      rescue ::JSON::ParserError => ex
        raise Errors::InvalidConfig, ex
      end

      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

      # Reload the current configuration file from disk
      #
      # @return [Buff::Config::JSON]
      def reload
        mass_assign(self.class.from_file(path).to_hash)
        self
      end
    end
  end
end