Class: Inspec::Resources::CsvConfig

Inherits:
JsonConfig show all
Defined in:
lib/inspec/resources/csv.rb

Instance Attribute Summary

Attributes inherited from JsonConfig

#params, #raw_content

Instance Method Summary collapse

Methods inherited from JsonConfig

#initialize, #method_missing, #to_s

Methods included from FileReader

#read_file_content

Methods included from ObjectTraverser

#extract_value

Constructor Details

This class inherits a constructor from Inspec::Resources::JsonConfig

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Inspec::Resources::JsonConfig

Instance Method Details

#parse(content) ⇒ Object

override the parse method from JsonConfig Assuming a header row of name,col1,col2, it will output an array of hashes like so:

[
  { 'name' => 'row1', 'col1' => 'value1', 'col2' => 'value2' },
  { 'name' => 'row2', 'col1' => 'value3', 'col2' => 'value4' }
]


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/inspec/resources/csv.rb', line 22

def parse(content)
  require "csv"

  # convert empty field to nil
  CSV::Converters[:blank_to_nil] = lambda do |field|
    field && field.empty? ? nil : field
  end

  # implicit conversion of values
  csv = CSV.new(content, headers: true, converters: %i{all blank_to_nil})

  # convert to hash
  csv.to_a.map(&:to_hash)
rescue => e
  raise Inspec::Exceptions::ResourceFailed, "Unable to parse CSV: #{e.message}"
end

#value(key) ⇒ Object

override the value method from JsonConfig The format of the CSV hash as created by #parse is very different than what the YAML, JSON, and INI resources create, so using the #value method from JsonConfig (which uses ObjectTraverser.extract_value) doesn’t make sense here.



44
45
46
# File 'lib/inspec/resources/csv.rb', line 44

def value(key)
  @params.map { |x| x[key.first.to_s] }.compact
end