Class: RuboCop::Cop::Iotventure::AdditionalProperties

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/iotventure/additional_properties.rb

Overview

This cop checks that every array and object schema has additionalProperties (defined or set to false). Note: This only works for schemas defined as Ruby hashes.

Examples:


# bad

  {
    type: :object,
    properties: {
      foo: { type: :string },
      bar: { type: :boolean }
    }
  }

# bad

  {
    type: :object,
    properties: {
      foo: { type: :string },
      bar: { type: :boolean }
    },
    additionalProperties: true
  }

# good

  {
    type: :object,
    properties: {
      foo: { type: :string },
      bar: { type: :boolean }
    },
    additionalProperties: false
  }

Constant Summary collapse

MISSING_MSG =
'Schema is missing additionalProperties. ' \
'Please add it to the schema at %<current>s'
ALWAYS_TRUE_MSG =
'Schema has additionalProperties set to true. ' \
'Please set it to false or define a rule at %<current>s'

Instance Method Summary collapse

Instance Method Details

#always_true_schema?(node) ⇒ Object



72
73
74
75
76
77
# File 'lib/rubocop/cop/iotventure/additional_properties.rb', line 72

def_node_matcher :always_true_schema?, <<~PATTERN
  {
    (true)
    (hash) # Empty hash is also always true in JSON Schema
  }
PATTERN

#on_hash(node) ⇒ Object



79
80
81
82
83
84
85
86
# File 'lib/rubocop/cop/iotventure/additional_properties.rb', line 79

def on_hash(node)
  return unless schema_object_definition_with_properties?(node)

  additional_properties = node.pairs.find { |pair| pair.key.value == :additionalProperties }
  return add_missing_offense(node) unless additional_properties

  add_always_true_offense(node) if always_true_schema?(additional_properties.value)
end

#schema_definition_with_properties?(node) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/iotventure/additional_properties.rb', line 57

def_node_matcher :schema_object_definition_with_properties?, <<~PATTERN
  (hash<
    (pair
      (sym :type)
      {(sym :object) (str "object")}
    )
    (pair
      <{(sym :properties) (sym :patternProperties)}>
      ...
    )
    ...
  >)
PATTERN