Sha256: 486785539957019963d2df5362cfd8d675f25a076b7b8cb3704572ce6720675f

Contents?: true

Size: 1.49 KB

Versions: 3

Compression:

Stored size: 1.49 KB

Contents

require 'multi_json'

module Chozo
  module Config
    module JSON
      extend ActiveSupport::Concern
      include Chozo::Config

      module ClassMethods
        # @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)
          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 = {})
        self.attributes = MultiJson.decode(json, options)
        self
      rescue MultiJson::DecodeError => e
        raise Chozo::Errors::InvalidConfig, e
      end

      def save(destination = self.path)
        FileUtils.mkdir_p(File.dirname(destination))
        File.open(destination, 'w+') do |f|
          f.write(self.to_json)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chozo-0.0.3 lib/chozo/config/json.rb
chozo-0.0.2 lib/chozo/config/json.rb
chozo-0.0.1 lib/chozo/config/json.rb