Sha256: d612543cc32107da1d70a837821bd35f57e2588e97719c5a715783fa4e261095

Contents?: true

Size: 1.91 KB

Versions: 2

Compression:

Stored size: 1.91 KB

Contents

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

module Quandl
module Command
class QConfig
  
  class << self
    
    def configuration
      @configuration ||= self.new( config_file: config_file )
    end
    
    def config_file
      return @config_file if defined?(@config_file)
      @config_file = File.join(root_path, 'config')
      convert_legacy_config
      ensure_directory_is_present
      @config_file
    end
    
    def root_path
      @root_path ||= File.join(ENV['HOME'], '.quandl')
    end
    
    protected
    
    def ensure_directory_is_present
      return if File.exists?(config_file)
      FileUtils.mkdir(root_path) unless Dir.exists?(root_path)
      File.write( config_file, YAML.dump({}) )
    end
    
    def convert_legacy_config
      return if File.directory?(root_path) || !File.exists?(root_path)
      # otherwise move the old .quandl into .quandl/config
      FileUtils.mv(root_path, "#{root_path}.old")
      FileUtils.mkdir(root_path)
      token = File.read("#{root_path}.old")
      File.write(config_file, "token: #{token}")
    end
    
    def define_attributes(*attr_names)
      attr_names.each do |attr_name|
        define_attribute(attr_name)
      end
    end
    
    def define_attribute(name)
      define_method(name){ read_attribute(name) }
      define_method("#{name}="){|v| write_attribute(name, v) }
    end
    
  end
  
  attr_accessor :options
  
  define_attributes :token, :quandl_url, :last_checked_for_update
  
  def initialize(*args)
    self.options = OpenStruct.new(args.extract_options!)
  end
  
  def config
    @config ||= OpenStruct.new(YAML.load(File.read(options.config_file)))
  end
  
  private
  
  def read_attribute(name)
    config.send(name)
  end
  
  def write_attribute(name, value)
    config.send("#{name}=", value)
    commit_config
  end
  
  def commit_config
    File.write( options.config_file, YAML.dump(config.marshal_dump) )
  end
  
end
end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
quandl-0.2.27 lib/quandl/command/qconfig.rb
quandl-0.2.26 lib/quandl/command/qconfig.rb