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.



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

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



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

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



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

def params
  @params
end

#raw_contentObject (readonly)

make params readable



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

def raw_content
  @raw_content
end

Instance Method Details

#to_sObject



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

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

#value(key) ⇒ Object



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

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