Class: CMDB::FileSource
- Inherits:
-
Object
- Object
- CMDB::FileSource
- 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.
Class Attribute Summary collapse
-
.base_directories ⇒ Object
Returns the value of attribute base_directories.
Instance Attribute Summary collapse
-
#prefix ⇒ URI
readonly
A file:// URL describing where this source’s data comes from.
-
#url ⇒ URI
readonly
A file:// URL describing where this source’s data comes from.
Instance Method Summary collapse
-
#each_pair {|key, value| ... } ⇒ Object
Enumerate the keys in this source, and their values.
-
#get(key) ⇒ nil, ...
Get the value of key.
-
#initialize(filename, root = nil, prefix = File.basename(filename, '.*')) ⇒ FileSource
constructor
Construct a new FileSource from an input YML file.
Constructor Details
#initialize(filename, root = nil, prefix = File.basename(filename, '.*')) ⇒ FileSource
Construct a new FileSource from an input YML file.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/cmdb/file_source.rb', line 34 def initialize(filename, root = nil, prefix = File.basename(filename, '.*')) @data = {} @prefix = prefix filename = File.(filename) @url = URI.parse("file://#{filename}") @extension = File.extname(filename) 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(url, 'file with unknown extension; expected js(on) or y(a)ml') end rescue StandardError raise BadData.new(url, 'CMDB data file') end raw_data = raw_data[root] if !root.nil? && raw_data.key?(root) flatten(raw_data, @prefix, @data) end |
Class Attribute Details
.base_directories ⇒ Object
Returns the value of attribute base_directories.
21 22 23 |
# File 'lib/cmdb/file_source.rb', line 21 def base_directories @base_directories end |
Instance Attribute Details
#prefix ⇒ URI (readonly)
Returns a file:// URL describing where this source’s data comes from.
14 15 16 |
# File 'lib/cmdb/file_source.rb', line 14 def prefix @prefix end |
#url ⇒ URI (readonly)
Returns a file:// URL describing where this source’s data comes from.
14 15 16 |
# File 'lib/cmdb/file_source.rb', line 14 def url @url end |
Instance Method Details
#each_pair {|key, value| ... } ⇒ Object
Enumerate the keys in this source, and their values.
72 73 74 75 |
# File 'lib/cmdb/file_source.rb', line 72 def each_pair(&_block) # Strip the prefix in the key and call the block @data.each_pair { |k, v| yield(k.split("#{@prefix}.").last, v) } end |
#get(key) ⇒ nil, ...
Get the value of key.
63 64 65 |
# File 'lib/cmdb/file_source.rb', line 63 def get(key) @data[key] end |