Class: ValidatedObject::Base Abstract

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Includes:
ActiveModel::Validations, SimplifiedApi
Defined in:
lib/validated_object.rb

Overview

This class is abstract.

Subclass and add attr_accessor and validations to create custom validating objects.

Uses ActiveModel::Validations to create self-validating Plain Old Ruby objects. This is especially useful when importing data from one system into another. This class also creates very readable error messages.

Examples:

Writing a self-validating object

class Dog < ValidatedObject::Base
  attr_accessor :name, :birthday

  validates :name, presence: true
  validates :birthday, type: Date, allow_nil: true
end

Instantiating and automatically validating

# The dog1 instance validates itself at the end of instantiation.
# Here, it succeeds and so doesn't raise an exception.
dog1 = Dog.new name: 'Spot'

# We can also explicitly test for validity
dog1.valid?  # => true

dog1.birthday = Date.new(2015, 1, 23)
dog1.valid?  # => true

Making an instance invalid

dog1.birthday = '2015-01-23'
dog1.valid?  # => false
dog1.check_validations!  # => ArgumentError: Birthday is class String, not Date

See Also:

Defined Under Namespace

Classes: Boolean, TypeValidator

Constant Summary collapse

SymbolHash =
T.type_alias { T::Hash[Symbol, T.untyped] }
EMPTY_HASH =
T.let({}.freeze, SymbolHash)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = EMPTY_HASH) ⇒ Base

Returns a new instance of Base.



70
71
72
73
74
# File 'lib/validated_object.rb', line 70

def initialize(attributes = EMPTY_HASH)
  set_instance_variables from_hash: attributes
  check_validations!
  nil
end

Class Method Details

.validated(*args, **kwargs, &block) ⇒ Object

Allow ‘validated’ as a synonym for ‘validates’



160
161
162
# File 'lib/validated_object.rb', line 160

def self.validated(*args, **kwargs, &block)
  validates(*args, **kwargs, &block)
end

Instance Method Details

#check_validations!Object

Raises:

  • (ArgumentError)


86
87
88
89
90
# File 'lib/validated_object.rb', line 86

def check_validations!
  raise ArgumentError, errors.full_messages.join('; ') if invalid?

  self
end

#validated_attr(attribute_name, **validation_options) ⇒ Object



76
77
78
79
# File 'lib/validated_object.rb', line 76

def validated_attr(attribute_name, **validation_options)
  attr_reader attribute_name
  validates attribute_name, validation_options
end