class Stannum::Constraints::Hashes::IndifferentKey

Constraint for validating an indifferent hash key.

To be a valid indifferent Hash key, an object must be a String or a Symbol and cannot be empty.

@example With nil

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?(nil) #=> false
constraint.errors_for(nil)
#=> [{ type: 'absent', data: {}, path: [], message: nil }]

@example With an Object

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?(Object.new.freeze) #=> false
constraint.errors_for(Object.new.freeze)
#=> [{ type: 'is_not_string_or_symbol', data: {}, path: [], message: nil }]

@example With an empty String

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?('') #=> false
constraint.errors_for('')
#=> [{ type: 'absent', data: {}, path: [], message: nil }]

@example With a String

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?('a string') #=> true

@example With an empty Symbol

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?(:'') #=> false
constraint.errors_for(:'')
#=> [{ type: 'absent', data: {}, path: [], message: nil }]

@example With a Symbol

constraint = Stannum::Constraints::Hashes::IndifferentKey.new
constraint.matches?(:a_symbol) #=> true

Constants

NEGATED_TYPE

The :type of the error generated for a matching object.

TYPE

The :type of the error generated for a non-matching object.

Public Instance Methods

errors_for(actual, errors: nil) click to toggle source

(see Stannum::Constraints::Base#errors_for)

Calls superclass method Stannum::Constraints::Base#errors_for
# File lib/stannum/constraints/hashes/indifferent_key.rb, line 50
def errors_for(actual, errors: nil)
  errors ||= Stannum::Errors.new

  return errors.add(Stannum::Constraints::Presence::TYPE) if actual.nil?

  return super unless indifferent_key_type?(actual)

  return errors unless actual.empty?

  errors.add(Stannum::Constraints::Presence::TYPE)
end
match?(actual)
Alias for: matches?
matches?(actual) click to toggle source

@return [true, false] true if the object is a non-empty String or Symbol.

# File lib/stannum/constraints/hashes/indifferent_key.rb, line 63
def matches?(actual)
  indifferent_key_type?(actual) && !actual.empty?
end
Also aliased as: match?

Private Instance Methods

indifferent_key_type?(actual) click to toggle source
# File lib/stannum/constraints/hashes/indifferent_key.rb, line 70
def indifferent_key_type?(actual)
  actual.is_a?(String) || actual.is_a?(Symbol)
end