Sha256: 992b084812ae0883d57c251bea02978af10b00749aaf172d23a377248774ab24

Contents?: true

Size: 858 Bytes

Versions: 3

Compression:

Stored size: 858 Bytes

Contents

require 'yaml'

module NestConnect
  class ConfigStore
    def initialize(path)
      @path = path
    end

    def [](key)
      data[key]
    end

    def save(key, value)
      data[key] = value

      find_or_create_directory
      find_or_create_file
      persist_data

      value
    end

    private

      attr_reader :path

      def find_or_create_directory
        Dir.mkdir(pathname.dirname) unless Dir.exist?(pathname.dirname)
      end

      def find_or_create_file
        File.new(path, "w") unless File.exists?(path)
      end

      def persist_data
        File.open(path, "w") { |f| f.write(data.to_yaml) }
      end

      def pathname
        Pathname.new(path)
      end

      def data
        @_data ||= load_data
      end

      def load_data
        YAML.load(File.read(path)) || {}
      rescue
        {}
      end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nest_connect-0.1.3 lib/nest_connect/config_store.rb
nest_connect-0.1.2 lib/nest_connect/config_store.rb
nest_connect-0.1.1 lib/nest_connect/config_store.rb