Class: LogSnag::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/logsnag/validator.rb

Overview

Provides helpers for validating data.

Class Method Summary collapse

Class Method Details

.compact_hash!(hash, path) ⇒ Hash

Removes any nil values from the hash at the specified path.

Parameters:

  • hash (Hash)

    The hash from which to remove nil values.

  • path (Symbol)

    The path to the hash to be compacted.

Returns:

  • (Hash)

    The hash with nil values removed.



30
31
32
33
# File 'lib/logsnag/validator.rb', line 30

def self.compact_hash!(hash, path)
  hash[path] = hash[path].compact if hash[path]
  hash
end

.validate_allowed_keys(allowed_keys, data) ⇒ void

This method returns an undefined value.

Ensure that the ‘data` hash only contains keys in the `allowed_keys` array.

Parameters:

  • allowed_keys (Array<Symbol>)

    The keys that are allowed in the hash.

  • data (Hash)

    The hash to be validated.

Raises:

  • (ArgumentError)

    If the hash contains invalid keys.



21
22
23
24
# File 'lib/logsnag/validator.rb', line 21

def self.validate_allowed_keys(allowed_keys, data)
  invalid_keys = data.keys - allowed_keys
  raise ArgumentError, "Found invalid keys: #{invalid_keys}" unless invalid_keys.empty?
end

.validate_hash(hash) ⇒ void

This method returns an undefined value.

Ensures that the keys and values in the hash conform to the specified rules.

Parameters:

  • hash (Hash)

    The hash to be validated.

Raises:

  • (ArgumentError)

    If the hash contains invalid keys or values.



39
40
41
42
43
44
45
46
47
# File 'lib/logsnag/validator.rb', line 39

def self.validate_hash(hash)
  return unless hash

  hash.each do |key, value|
    raise ArgumentError, "Invalid key: '#{key}'. Keys must be lowercase and may include dashes." unless key.to_s.match?(/\A[a-z]+(-[a-z]+)*\z/)

    raise ArgumentError, "Invalid value for '#{key}': '#{value}'. Values must be a string, boolean, or number." unless [String, TrueClass, FalseClass, Numeric].any? { |type| value.is_a?(type) }
  end
end

.validate_required_keys(required_keys, data) ⇒ void

This method returns an undefined value.

Ensure that the ‘required_keys` are present in the `data` hash.

Parameters:

  • required_keys (Array<Symbol>)

    The keys that must be present in the hash.

  • data (Hash)

    The hash to be validated.

Raises:

  • (ArgumentError)

    If the hash is missing required keys.



11
12
13
14
# File 'lib/logsnag/validator.rb', line 11

def self.validate_required_keys(required_keys, data)
  missing_keys = required_keys - data.keys
  raise ArgumentError, "Missing required keys: #{missing_keys}" unless missing_keys.empty?
end