Sha256: 5e67f78fac74446b33202988e44e744c04f2fc8b3fca9a4237171744452be7b7

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

require 'yaml'

module Stastic
  module Config
    extend self

    VALID_SETTINGS = %w(user token name site_id site_root host)
    def exists?
      File.exists?(config_path) || File.exists?(global_path)
    end
    
    def credentials?
      exists? && user && token
    end

    def site_defined?
      credentials? && site_id
    end

    def update(attrs, scope = nil)
      if scope == :global
        @global_config = update_config(attrs, global_config, global_path)
      else
        @config = update_config(attrs, config, config_path)
      end
    end

    alias_method :add, :update

    def reset
      @config = nil
      @global_config = nil
    end

    VALID_SETTINGS.each do |key|
      define_method key do
        get(key.to_sym)
      end
    end

    private
      def update_config(attrs, config_obj, persist_path)
        updated_config = config_obj.merge(attrs)
        File.open(persist_path, "w") do |f|
          f.write(updated_config.to_yaml)
        end
        updated_config
      end

      def stored_config(path)
        if File.exists?(path)
          YAML.load(File.read(path))
        else
          {}
        end
      end

      def get(key)
        config[key] || global_config[key]
      end

      def config
        @config ||= stored_config(config_path)
      end

      def global_config
        @global_config ||= stored_config(global_path)
      end

      def config_path
        File.expand_path(".stastic")
      end

      def global_path
        File.expand_path("~/.stastic")
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
stastic-0.2.7 lib/stastic/config.rb