require 'fileutils' require 'yaml' require 'ostruct' require 'quandl/support/attributes' module Quandl module Command class Config include Quandl::Support::Attributes define_attributes :token, :quandl_url, :last_checked_for_update, :output_format, :send_crash_reports, :stdout, :stderr attr_accessor :options def initialize(opts={}) self.options = opts.symbolize_keys convert_legacy_config ensure_directory_is_present @attributes = read_config_from_file.stringify_keys end def stdout options[:stdout] || read_attribute(:stdout) end def stderr options[:stderr] || read_attribute(:stderr) end def quandl_url return @quandl_url if @quandl_url.present? @quandl_url = options[:url] if options[:url].present? @quandl_url = ENV['QUANDL_URL'] if @quandl_url.blank? @quandl_url = read_attribute(:quandl_url) if @quandl_url.blank? @quandl_url = 'http://quandl.com/api/' if @quandl_url.blank? @quandl_url end def auth_token return @auth_token if @auth_token.present? @auth_token = options[:token] if options[:token].present? @auth_token = ENV['QUANDL_TOKEN'] if @auth_token.blank? @auth_token = read_attribute(:token) if @auth_token.blank? @auth_token end def request_platform 'sandbox' if options[:sandbox].present? end def file_path options[:file_path] end def file_dir File.dirname(file_path) end private def ensure_directory_is_present return if File.exists?(file_path) FileUtils.mkdir(file_dir) unless Dir.exists?(file_dir) File.write( file_path, YAML.dump({}) ) end def convert_legacy_config return if File.directory?(file_dir) || !File.exists?(file_dir) # otherwise move the old .quandl into .quandl/config FileUtils.mv(file_dir, "#{file_dir}.old") FileUtils.mkdir(file_dir) token = File.read("#{file_dir}.old") File.write(file_path, "token: #{token}") end def write_attribute(*args) super(*args) write_config_to_file end def read_config_from_file YAML.load(File.read(file_path)) end def write_config_to_file File.write( file_path, YAML.dump(attributes) ) end end end end