Sha256: 659b19fca10e6e893393db79efb58a9004740de6b92d3c655b35e266f87584f7

Contents?: true

Size: 877 Bytes

Versions: 4

Compression:

Stored size: 877 Bytes

Contents

require 'yaml'
require 'pathname'

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

4 entries across 4 versions & 1 rubygems

Version Path
nest_connect-0.1.7 lib/nest_connect/config_store.rb
nest_connect-0.1.6 lib/nest_connect/config_store.rb
nest_connect-0.1.5 lib/nest_connect/config_store.rb
nest_connect-0.1.4 lib/nest_connect/config_store.rb