Sha256: 61a70f67ff681542099a4e84b1237040bab271575c0060ea2461646b8baf69a7

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

require 'ostruct'
require 'yaml'
require 'fileutils'

class String
  def undent
    gsub(/^.{#{slice(/^ +/).length}}/, '')
  end
end

module Nv
  class Config < OpenStruct
    def initialize(config_path)
      # Initialize config file
      @config_path = config_path
      config_dir = File.dirname(@config_path)

      Dir.mkdir(config_dir) unless Dir.exist?(config_dir)
      FileUtils.touch(@config_path) unless File.exist?(@config_path)

      @config = YAML.load(open(@config_path).read) || {}
      super(@config)
    end

    def save
      File.open(@config_path, 'w') do |f|
        f.print YAML.dump(transform_keys(self.to_h){|k| k.to_s})
      end
    end

    def verify_for_authentication
      self.email && self.password
    end

    def verify_for_authentication!(cmd)
      unless verify_for_authentication
        puts <<-EOD.undent
        `nv #{cmd}` should be given email and password.
        $ nv config email <email>
        $ nv config password <password>
        EOD
        exit
      end
    end

    private

    def transform_keys(hs)
      result = {}
      hs.each_key do |key|
        result[yield(key)] = hs[key]
      end
      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nv-1.2.2 lib/nv/config.rb