Class: DiscoveryV1::Validation::ValidateObject

Inherits:
Object
  • Object
show all
Defined in:
lib/discovery_v1/validation/validate_object.rb

Overview

Validate objects against a Google Discovery V1 API request object schema

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rest_description:, logger: Logger.new(nil)) ⇒ ValidateObject

Create a new api object validator

By default, a nil logger is used. This means that no messages are logged.

Examples:

validator = DiscoveryV1::Validation::ValidateObject.new

Parameters:

  • logger (Logger) (defaults to: Logger.new(nil))

    the logger to use



21
22
23
24
# File 'lib/discovery_v1/validation/validate_object.rb', line 21

def initialize(rest_description:, logger: Logger.new(nil))
  @rest_description = rest_description
  @logger = logger
end

Instance Attribute Details

#loggerLogger (readonly)

The logger to use internally

Validation errors are logged at the error level. Other messages are logged at the debug level.

Examples:

logger = Logger.new(STDOUT, :level => Logger::INFO)
validator = DiscoveryV1::Validation::ValidateObject.new(logger)
validator.logger == logger # => true
validator.logger.debug { "Debug message" }

Returns:

  • (Logger)


50
51
52
# File 'lib/discovery_v1/validation/validate_object.rb', line 50

def logger
  @logger
end

#rest_descriptionGoogle::Apis::DiscoveryV1::RestDescription (readonly)

The Google Discovery V1 API description containing schemas to use for validation

Examples:

rest_description = DiscoveryV1.discovery_service.get_rest_description('sheets', 'v4')
validator = DiscoveryV1::Validation::ValidateObject.new(rest_description:)
validator.rest_description == rest_description # => true

Returns:



35
36
37
# File 'lib/discovery_v1/validation/validate_object.rb', line 35

def rest_description
  @rest_description
end

Instance Method Details

#call(schema_name:, object:) ⇒ void

This method returns an undefined value.

Validate the object using the JSON schema named schema_name

Examples:

schema_name = 'batch_update_spreadsheet_request'
object = { 'requests' => [] }
validator = DiscoveryV1::Validation::ValidateObject.new
validator.call(schema_name:, object:)

Parameters:

  • schema_name (String)

    the name of the schema to validate against

  • object (Object)

    the object to validate

Raises:

  • (RuntimeError)

    if the object does not conform to the schema



67
68
69
70
71
72
73
74
75
76
# File 'lib/discovery_v1/validation/validate_object.rb', line 67

def call(schema_name:, object:)
  logger.debug { "Validating #{object} against #{schema_name}" }

  schema = { '$ref' => schema_name }
  schemer = JSONSchemer.schema(schema, ref_resolver:)
  errors = schemer.validate(object)
  raise_error!(schema_name, object, errors) if errors.any?

  logger.debug { "Object #{object} conforms to #{schema_name}" }
end