Sha256: 84d730d65cc77f62493e4d52dc04e77ca4cb31e23332f68b1e311d87bc5896c2

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

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 [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(self.to_json(pretty: true))
        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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
buff-config-0.1.1 lib/buff/config/json.rb