Sha256: c7e8fadcc31a3b69c383aaf7eca73c996134132035213c8e88b6209d1599f3a4

Contents?: true

Size: 1.73 KB

Versions: 2

Compression:

Stored size: 1.73 KB

Contents

require 'chozo/errors'
require 'multi_json'

module Chozo
  module Config
    # @author Jamie Winsor <jamie@vialstudios.com>
    class JSON < Config::Abstract
      class << self
        # @param [String] data
        #
        # @return [~Chozo::Config::JSON]
        def from_json(data)
          new.from_json(data)
        end

        # @param [String] path
        #
        # @raise [Chozo::Errors::ConfigNotFound]
        #
        # @return [~Chozo::Config::JSON]
        def from_file(path)
          path = File.expand_path(path)
          data = File.read(path)
          new(path).from_json(data)
        rescue Errno::ENOENT, Errno::EISDIR
          raise Chozo::Errors::ConfigNotFound, "No configuration found at: '#{path}'"
        end
      end

      # @param (see MultiJson.encode) options
      #
      # @return [String]
      def to_json(options = {})
        MultiJson.encode(self.attributes, options)
      end
      alias_method :as_json, :to_json

      # @param (see MultiJson.decode) json
      # @param (see MultiJson.decode) options
      #
      # @raise [Chozo::Errors::InvalidConfig]
      #
      # @return [~Chozo::Config::JSON]
      def from_json(json, options = {})
        mass_assign(MultiJson.decode(json, options))
        self
      rescue MultiJson::DecodeError => e
        raise Chozo::Errors::InvalidConfig, e
      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
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
chozo-0.2.3 lib/chozo/config/json.rb
chozo-0.2.2 lib/chozo/config/json.rb