Class: Birdwatcher::Configuration

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/birdwatcher/configuration.rb

Defined Under Namespace

Classes: ConfigurationFileCorrupt, ConfigurationFileNotFound, ConfigurationFileNotReadable, Error, UnknownKey

Constant Summary collapse

CONFIGURATION_FILE_NAME =
".birdwatcherrc".freeze
CONFIGURATION_FILE_LOCATION =
File.join(Dir.home, CONFIGURATION_FILE_NAME).freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configured?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/birdwatcher/configuration.rb', line 24

def self.configured?
  File.exist?(CONFIGURATION_FILE_LOCATION)
end

.get(key) ⇒ Object



18
19
20
21
22
# File 'lib/birdwatcher/configuration.rb', line 18

def self.get(key)
  self.instance.get!(key)
rescue Birdwatcher::Configuration::UnknownKey
  nil
end

.get!(key) ⇒ Object



14
15
16
# File 'lib/birdwatcher/configuration.rb', line 14

def self.get!(key)
  self.instance.get!(key)
end

.load!Object



34
35
36
# File 'lib/birdwatcher/configuration.rb', line 34

def self.load!
  self.instance.load_configuration!
end

.save!(configuration) ⇒ Object



28
29
30
31
32
# File 'lib/birdwatcher/configuration.rb', line 28

def self.save!(configuration)
  File.open(CONFIGURATION_FILE_LOCATION, "w") do |f|
    f.write(YAML.dump(configuration))
  end
end

Instance Method Details

#get!(key) ⇒ Object



50
51
52
53
54
# File 'lib/birdwatcher/configuration.rb', line 50

def get!(key)
  key = key.to_sym
  fail(UnknownKey, "Unknown configuration key: #{key}") unless configuration.key?(key)
  configuration[key.to_sym]
end

#load_configuration!Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/birdwatcher/configuration.rb', line 38

def load_configuration!
  if !File.exist?(CONFIGURATION_FILE_LOCATION)
    fail ConfigurationFileNotFound, "Configuration file does not exist"
  end
  if !File.readable?(CONFIGURATION_FILE_LOCATION)
    fail ConfigurationFileNotReadable, "Configuration file is not readable"
  end
  @configuration = YAML.load_file(CONFIGURATION_FILE_LOCATION).inject({}) { |memo, (k,v)| memo[k.to_sym] = v; memo }
rescue ::Psych::SyntaxError => e
  raise ConfigurationFileCorrupt, "Configuration file contains invalid YAML"
end