Class: CMDB::Source::File

Inherits:
CMDB::Source show all
Defined in:
lib/cmdb/source/file.rb

Overview

Data source that is backed by a YAML/JSON file that lives in the filesystem. The name of the file becomes the top-level key under which all values in the file are exposed, preserving their exact structure as parsed by YAML/JSON.

Examples:

Use my.yml as a CMDB source

source = Source::File.new('/tmp/my.yml') # contains a top-level stanza named "database"
source['my']['database']['host'] # => 'db1-1.example.com'

Instance Attribute Summary

Attributes inherited from CMDB::Source

#prefix, #uri

Instance Method Summary collapse

Methods inherited from CMDB::Source

create, detect

Constructor Details

#initialize(uri, prefix) ⇒ File

Read a data file whose location is specified by a file:// URI.

Parameters:

  • uri (URI)

    logical description of this source

  • prefix (String)

    unique dot-notation prefix of all this source’s keys, if any

Raises:

  • (BadData)

    if the file’s content is malformed



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
# File 'lib/cmdb/source/file.rb', line 18

def initialize(uri, prefix)
  super(uri, prefix)
  path = @uri.path
  filename  = ::File.basename(path)
  extension = ::File.extname(filename)
  raw_bytes = ::File.read(path)
  raw_data  = nil

  begin
    case extension
    when /jso?n?$/i
      raw_data = JSON.load(raw_bytes)
    when /ya?ml$/i
      raw_data = YAML.load(raw_bytes)
    else
      raise BadData.new(@uri, 'file with unknown extension; expected js(on) or y(a)ml')
    end
  rescue StandardError
    raise BadData.new(@uri, 'CMDB data file')
  end

  @data = {}
  flatten(raw_data, @prefix, @data)

  # File sources are static; we can check them for data errors at load
  # time. Do this by each'ing, which validates values as a side effect.
  each_pair { |_,_| }
end

Instance Method Details

#each_pair {|key, value| ... } ⇒ Object

Enumerate the keys and values in this source.

Yields:

  • every key/value in the source

Yield Parameters:

  • key (String)
  • value (Object)


60
61
62
63
64
65
# File 'lib/cmdb/source/file.rb', line 60

def each_pair(&_block)
  @data.each_pair do |key, value|
    validate!(key, value)
    yield(key, value)
  end
end

#get(key) ⇒ Object

Get the value of key.

Returns:

  • (Object)

    the key’s value, or nil if not found



50
51
52
53
# File 'lib/cmdb/source/file.rb', line 50

def get(key)
  value = @data[key]
  validate!(key, value)
end