Sha256: e3eb85f0093edb1f342f8b54f90cfc4767caaa7e6382e7a3c287dba84d400c24

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

require 'singleton'

class RCFile
  FILE_NAME = '.trc'
  attr_reader :path

  include Singleton

  def initialize
    @path = File.join(File.expand_path("~"), FILE_NAME)
    @data = load
  end

  def [](username)
    profiles[username]
  end

  def []=(username, profile)
    profiles[username] ||= {}
    profiles[username].merge!(profile)
    write
  end

  def configuration
    @data['configuration']
  end

  def active_consumer_key
    profiles[active_profile[0]][active_profile[1]]['consumer_key'] if active_profile && profiles[active_profile[0]] && profiles[active_profile[0]][active_profile[1]]
  end

  def active_consumer_secret
    profiles[active_profile[0]][active_profile[1]]['consumer_secret'] if active_profile && profiles[active_profile[0]] && profiles[active_profile[0]][active_profile[1]]
  end

  def active_profile
    configuration['default_profile']
  end

  def active_profile=(profile)
    configuration['default_profile'] = [profile['username'], profile['consumer_key']]
    write
  end

  def active_secret
    profiles[active_profile[0]][active_profile[1]]['secret'] if active_profile && profiles[active_profile[0]] && profiles[active_profile[0]][active_profile[1]]
  end

  def active_token
    profiles[active_profile[0]][active_profile[1]]['token'] if active_profile && profiles[active_profile[0]] && profiles[active_profile[0]][active_profile[1]]
  end

  def delete
    File.delete(@path) if File.exist?(@path)
  end

  def empty?
    @data == default_structure
  end

  def load
    require 'yaml'
    YAML.load_file(@path)
  rescue Errno::ENOENT
    default_structure
  end

  def path=(path)
    @path = path
    @data = load
    @path
  end

  def profiles
    @data['profiles']
  end

  def reset
    self.send(:initialize)
  end

private

  def default_structure
    {'configuration' => {}, 'profiles' => {}}
  end

  def write
    require 'yaml'
    File.open(@path, File::RDWR|File::TRUNC|File::CREAT, 0600) do |rcfile|
      rcfile.write @data.to_yaml
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
t-0.9.9 lib/t/rcfile.rb
t-0.9.8 lib/t/rcfile.rb