Sha256: 19ce9bfc153c0df79657539bcd7f4061fc2e712f1c5a501b5c3ec5ea8397ae30

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true
require_relative "parser"

module LoadFile
  # A class to load `file` into Hash, find or create constant by `constant_name`.
  #
  # @return [Hash] parsed YAML or JSON content
  class Loader < Hash
    def initialize(file, constant_name)
      @file = file
      @constant = find_or_define(constant_name)

      update parsed_content
    end

    # Set `values` into `constant` if not exists.
    def set_constant
      each { |key, value| constant[key] ||= value }
    end

    # Override `values` into `constant`.
    def set_constant!
      each { |key, value| constant[key] = value }
    end

    private

    attr_reader :file, :constant

    def find_or_define(constant_name)
      if Object.const_defined?(constant_name)
        Object.const_get(constant_name)
      else
        Object.const_set(constant_name, {})
      end
    end

    def parsed_content
      case File.extname(file)
      when ".yml", ".yaml"
        Parser.yaml(content)
      when ".json"
        Parser.json(content)
      else
        raise_parser_error("don't know how to parse #{file}")
      end
    rescue Parser::ParserError
      raise_parser_error("#{file} format is invalid")
    end

    def raise_parser_error(message)
      raise Parser::ParserError, message
    end

    def content
      IO.read(file)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
load_file-1.0.0 lib/load_file/loader.rb