Class: CMDB::FileSource

Inherits:
Object
  • Object
show all
Defined in:
lib/cmdb/file_source.rb

Overview

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

Examples:

Use my.yml as a CMDB source

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

Constant Summary collapse

@@base_directories =
['/var/lib/cmdb', File.expand_path('~/.cmdb')]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, root = nil) ⇒ FileSource

Construct a new FileSource from an input YML file.

Raises:

  • (BadData)

    if the file’s content is malformed



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/cmdb/file_source.rb', line 31

def initialize(filename, root=nil)
  filename = File.expand_path(filename)
  @url = URI.parse("file://#{filename}")
  @prefix = File.basename(filename, ".*")
  @extension = File.extname(filename)
  @data = {}

  raw_bytes = File.read(filename)
  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(self.url, 'file with unknown extension; expected js(on) or y(a)ml')
    end
  rescue Exception
    raise BadData.new(self.url, 'CMDB data file')
  end

  raw_data = raw_data[root] if !root.nil? && raw_data.key?(root)
  flatten(raw_data, @prefix, @data)
end

Instance Attribute Details

#prefixURI (readonly)



13
14
15
# File 'lib/cmdb/file_source.rb', line 13

def prefix
  @prefix
end

#urlURI (readonly)



13
14
15
# File 'lib/cmdb/file_source.rb', line 13

def url
  @url
end

Class Method Details

.base_directoriesArray

List of directories that will be searched (in order) for YML files at load time.



19
20
21
# File 'lib/cmdb/file_source.rb', line 19

def self.base_directories
  @@base_directories
end

.base_directories=(bd) ⇒ Object



24
25
26
# File 'lib/cmdb/file_source.rb', line 24

def self.base_directories=(bd)
  @@base_directories = bd
end

Instance Method Details

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

Enumerate the keys in this source, and their values.

Yields:

  • every key/value in the source

Yield Parameters:

  • key (String)
  • value (Object)


70
71
72
73
# File 'lib/cmdb/file_source.rb', line 70

def each_pair(&block)
  # Strip the prefix in the key and call the block
  @data.each_pair { |k, v| block.call(k.split("#{@prefix}.").last, v) }
end

#get(key) ⇒ nil, ...

Get the value of key.



61
62
63
# File 'lib/cmdb/file_source.rb', line 61

def get(key)
  @data[key]
end