Module: Figly

Defined in:
lib/figly.rb,
lib/figly/version.rb,
lib/figly/settings.rb

Defined Under Namespace

Modules: Settings Classes: ConfigNotFoundError, ConfigNotLoaded, ParserError, UnsupportedFormatError

Constant Summary collapse

VERSION =
"1.1.0"

Class Method Summary collapse

Class Method Details

._config_loaded?Boolean

Returns:



79
80
81
# File 'lib/figly.rb', line 79

def self._config_loaded?
  defined?(@@data) && @@data
end

._deep_merge(first, second) ⇒ Object



68
69
70
71
# File 'lib/figly.rb', line 68

def self._deep_merge(first, second)
  merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
  first.merge!(second, &merger)
end

._ensure_loaded!Object



73
74
75
76
77
# File 'lib/figly.rb', line 73

def self._ensure_loaded!
  unless _config_loaded?
    raise ConfigNotLoaded, "You must first load the config before attempting to access it"
  end
end

.cleanObject

Useful for testing



59
60
61
# File 'lib/figly.rb', line 59

def self.clean
  @@data = nil
end

.dataObject



63
64
65
66
# File 'lib/figly.rb', line 63

def self.data
  _ensure_loaded!
  @@data
end

.load_file(path) ⇒ Object

Raises:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/figly.rb', line 10

def self.load_file(path)
  raise ConfigNotFoundError, "File does not exist: #{path}" unless File.exists?(path)
  ext = File.extname(path)
  data = case ext
  when '.toml'
    begin
      require 'toml'
      # HACK: TOML captures Parslet errors and puts them so they get swallowed
      # here we redirect stdout to an IO buffer that we can read from and test
      # that the value doesn't match an error
      old_stdout = $stdout
      $stdout = StringIO.new('','w')
      TOML.load_file(path).tap do |d|
        cap = $stdout.string
        raise ParserError, cap if cap =~ /^Failed to match/
      end
    rescue Exception => e
      raise ParserError, e.message
    ensure
      # Make sure to reset the old stdout even if an exception is thrown
      $stdout = old_stdout
    end
  when '.yml'
    begin
      require 'yaml'
      YAML.load_file(path)
    rescue Exception => e
      raise ParserError, e.message
    end
  when '.json'
    begin
      require 'json'
      JSON.parse(File.read(path))
    rescue Exception => e
      raise ParserError, e.message
    end
  else
    raise UnsupportedFormatError, "Unsupported file extension (#{ext})"
  end

  # Here we merge config files if there are multiple load calls
  if _config_loaded?
    _deep_merge(@@data, data)
  else
    @@data = data.extend(Settings::SettingsHash)
  end
end