Class: Inspec::Resources::JsonConfig

Inherits:
Object
  • Object
show all
Includes:
ObjectTraverser
Defined in:
lib/resources/json.rb

Direct Known Subclasses

CsvConfig, IniConfig, YamlConfig

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ObjectTraverser

#extract_value

Constructor Details

#initialize(path) ⇒ JsonConfig

Returns a new instance of JsonConfig.



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

def initialize(path)
  @path = path
  @file = inspec.file(@path)
  @file_content = @file.content

  # check if file is available
  if !@file.file?
    skip_resource "Can't find file \"#{@conf_path}\""
    return @params = {}
  end

  # check if file is readable
  if @file_content.empty? && @file.size > 0
    skip_resource "Can't read file \"#{@conf_path}\""
    return @params = {}
  end

  @params = parse(@file_content)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*keys) ⇒ Object

Shorthand to retrieve a parameter name via ‘#its`. Example: describe json(’file’) { its(‘paramX’) { should eq ‘Y’ } }

Parameters:

  • name (String)

    name of the field to retrieve

Returns:

  • (Object)

    the value stored at this position



56
57
58
59
60
61
# File 'lib/resources/json.rb', line 56

def method_missing(*keys)
  # catch bahavior of rspec its implementation
  # @see https://github.com/rspec/rspec-its/blob/master/lib/rspec/its.rb#L110
  keys.shift if keys.is_a?(Array) && keys[0] == :[]
  value(keys)
end

Instance Attribute Details

#paramsObject (readonly)

make params readable



20
21
22
# File 'lib/resources/json.rb', line 20

def params
  @params
end

Instance Method Details

#parse(content) ⇒ Object



42
43
44
45
# File 'lib/resources/json.rb', line 42

def parse(content)
  require 'json'
  JSON.parse(content)
end

#to_sObject



63
64
65
# File 'lib/resources/json.rb', line 63

def to_s
  "Json #{@path}"
end

#value(key) ⇒ Object



47
48
49
# File 'lib/resources/json.rb', line 47

def value(key)
  extract_value(key, @params)
end