Class: Inspec::Resources::JsonConfig

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

Direct Known Subclasses

CsvConfig, IniConfig, TomlConfig, XmlConfig, YamlConfig

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from FileReader

#read_file_content

Methods included from ObjectTraverser

#extract_value

Constructor Details

#initialize(opts) ⇒ JsonConfig

Returns a new instance of JsonConfig.



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/inspec/resources/json.rb', line 29

def initialize(opts)
  # pre-initialize @params to an empty hash. In the event that reading/parsing the data
  # throws an exception, this allows the resource to still be called outside of a
  # describe/test and not throw errors when a caller attempts to fetch a value from the params.
  @params = {}

  # load the raw content from the source, and then parse it
  @raw_content = load_raw_content(opts)
  @params = parse(@raw_content)

  # If the JSON content is enumerable, make this object enumerable too
  extend EnumerableDelegation if @params.respond_to?(:each)
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



48
49
50
51
52
53
# File 'lib/inspec/resources/json.rb', line 48

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



27
28
29
# File 'lib/inspec/resources/json.rb', line 27

def params
  @params
end

#raw_contentObject (readonly)

make params readable



27
28
29
# File 'lib/inspec/resources/json.rb', line 27

def raw_content
  @raw_content
end

Instance Method Details

#to_sObject



61
62
63
# File 'lib/inspec/resources/json.rb', line 61

def to_s
  "#{resource_base_name} #{@resource_name_supplement || "content"}"
end

#value(key) ⇒ Object



55
56
57
58
59
# File 'lib/inspec/resources/json.rb', line 55

def value(key)
  # uses ObjectTraverser.extract_value to walk the hash looking for the key,
  # which may be an Array of keys for a nested Hash.
  extract_value(key, params)
end