Class: Eaternet::ValidatedObject Abstract

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/eaternet/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.

Examples:

Writing a self-validating object

class Dog < Eaternet::ValidatedObject
  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 do |d|
  d.name = 'Spot'
end

# 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: TypeValidator

Instance Method Summary collapse

Constructor Details

#initialize {|new_object| ... } ⇒ ValidatedObject

Instantiate and validate a new object.

Yield Parameters:

  • new_object (ValidatedObject)

    the yielded new object for configuration.

Raises:

  • (ArgumentError)

    if the object is not valid at the end of initialization.



50
51
52
53
# File 'lib/eaternet/validated_object.rb', line 50

def initialize(&block)
  block.call(self)
  check_validations!
end

Instance Method Details

#check_validations!Object

Run any validations and raise an error if invalid.

Raises:

  • (ArgumentError)

    if any validations fail.



57
58
59
# File 'lib/eaternet/validated_object.rb', line 57

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