Class: CMDB::Source::File
- Inherits:
-
CMDB::Source
- Object
- CMDB::Source
- CMDB::Source::File
- 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.
Instance Attribute Summary
Attributes inherited from CMDB::Source
Instance Method Summary collapse
-
#each_pair {|key, value| ... } ⇒ Object
Enumerate the keys and values in this source.
-
#get(key) ⇒ Object
Get the value of key.
-
#initialize(uri, prefix) ⇒ File
constructor
Read a data file whose location is specified by a file:// URI.
Methods inherited from CMDB::Source
Constructor Details
#initialize(uri, prefix) ⇒ File
Read a data file whose location is specified by a file:// URI.
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.
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.
50 51 52 53 |
# File 'lib/cmdb/source/file.rb', line 50 def get(key) value = @data[key] validate!(key, value) end |