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

#method_missing, #to_s

Methods included from FileReader

#read_file_content

Methods included from ObjectTraverser

#extract_value

Constructor Details

#initialize(path, headers = true) ⇒ CsvConfig

Returns a new instance of CsvConfig.



20
21
22
23
24
# File 'lib/inspec/resources/csv.rb', line 20

def initialize(path, headers = true)
  @headers = headers
  @path = path
  super(@path)
end

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' }
]

When headers is set to false it will return data as array of array

[
  ['name', col1', 'col2'],
  ['row2', 'value3', 'value4']
]


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/inspec/resources/csv.rb', line 37

def parse(content)
  require "csv" unless defined?(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: @headers, converters: %i{all blank_to_nil})

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

#resource_idObject



72
73
74
# File 'lib/inspec/resources/csv.rb', line 72

def resource_id
  @path || "csv"
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.



63
64
65
66
67
68
69
70
# File 'lib/inspec/resources/csv.rb', line 63

def value(key)
  if @headers
    @params.map { |x| x[key.first.to_s] }.compact
  else
    # when headers is set to false send the array as it is.
    @params
  end
end