module Settings

Manages persistent (session-independent) application state.

Attributes

config_file_path[RW]

The path of the application's rc file.

dirty[RW]

true if the settings have been modified since last write, false otherwise.

settings[RW]

A Hash of setting keys to values.

Public Class Methods

[](key) click to toggle source

Return the value of a setting, or nil if the setting does not exist.

# File lib/droxi/settings.rb, line 11
def self.[](key)
  settings[key]
end
[]=(key, value) click to toggle source

Set the value of a setting.

# File lib/droxi/settings.rb, line 16
def self.[]=(key, value)
  return value if value == settings[key]
  self.dirty = true
  settings[key] = value
end
delete(key) click to toggle source

Delete the setting and return its value.

# File lib/droxi/settings.rb, line 28
def self.delete(key)
  return unless settings.include?(key)
  self.dirty = true
  settings.delete(key)
end
include?(key) click to toggle source

Return true if the setting exists, false otherwise.

# File lib/droxi/settings.rb, line 23
def self.include?(key)
  settings.include?(key)
end
read() click to toggle source

Read and parse the rc file.

# File lib/droxi/settings.rb, line 48
def self.read
  self.dirty = false
  return {} unless File.exist?(config_file_path)
  File.open(config_file_path) do |file|
    file.each_line.reduce({}) { |a, e| a.merge(parse(e.strip)) }
  end
end
save() click to toggle source

Write settings to disk.

# File lib/droxi/settings.rb, line 35
def self.save
  return unless dirty
  self.dirty = false
  require 'fileutils'
  FileUtils.mkdir_p(File.dirname(config_file_path))
  File.open(config_file_path, 'w') do |file|
    settings.each_pair { |k, v| file.write("#{k}=#{v}\n") }
    file.chmod(0600)
  end
  nil
end

Private Class Methods

init() click to toggle source

Initialize settings by reading rc file.

# File lib/droxi/settings.rb, line 85
def self.init
  self.settings = read
end
parse(line) click to toggle source

Parse a line of the rc file and return a Hash containing the resulting setting data.

# File lib/droxi/settings.rb, line 76
def self.parse(line)
  return warn_invalid(line) unless /^(.+?)=(.+)$/ =~ line
  key = Regexp.last_match[1].to_sym
  value = Regexp.last_match[2]
  return warn_invalid(line) unless [:access_token, :oldpwd].include?(key)
  { key => value }
end
warn_invalid(line) click to toggle source

Print a warning for an invalid setting and return an empty Hash (the result of an invalid setting).

# File lib/droxi/settings.rb, line 69
def self.warn_invalid(line)
  warn "invalid setting: #{line}"
  {}
end