Module: BetterValidations

Defined in:
lib/better_validations.rb,
lib/better_validations/railtie.rb,
lib/better_validations/version.rb

Overview

  1. A module provides a way to get error messages from an active record

keeping structure of nested objects represented by relations such as belongs_to, has_one, has_many instead of a flat structure. Just call:

active_record.errors.detailed_messages

This calling returns a hash such as:

{ field_one: ['Error 1', 'Error 2'],
  field_two: ['Error'],
  nested_object: { field: ['Error'] },
  nested_list: [{ field: ['Error'] }] }

A “detailed_messages” method has a “wrap_attributes_to” parameter. You can use it to wrap all attributes except relations by passed key:

active_record.errors.detailed_messages(wrap_attributes_to: :fields)
{ fields: { field_one: ['Error'], field_two: ['Error'] },
  nested_object: { fields: { field: ['Error'] } } }

This module also provides other features.

  1. Ability to validate nested objects in separated validators with

included ActiveModel::Validations.

Just include BetterValidations::Validator instead of ActiveModel::Validations and you will can to validate nested objects with the other validator by calling a “validate_nested” method:

class UserValidator
  include BetterValidations::Validator

  attr_accessor :email, :password, :personal_info

  validates_presence_of :email, :password
  validate_nested :personal_info, PersonalInfoValidator
end

class PersonalInfoValidator
  include BetterValidations::Validator

  attr_accessor :first_name, :last_name
  validates_presence_of :first_name, :last_name
end

After that you can validate active record object, hash or ActionController::Parameters by passing them to the validator. Keys “#field” and “#field_attributes” are synonyms and fills a “#field=” attr_accessor:

user = User.new(email: '', personal_info_attributes: { first_name: '' })
user = User.new(personal_info: PersonalInfo.new(last_name: ''))
user = { email: '', personal_info_attributes: { last_name: '' } }
user = { email: '', personal_info: { last_name: '' } }
user = ActionController::Parameters.new(email: '')

validator = UserValidator.new(user)
validator.valid?
validator.errors.detailed_messages
  1. Ability to merge validators in order to get merged detailed errors.

Useful when you needs to get errors from multiple validators or if a part of validations implemented inside a model. Usage:

validator = validator_one.merge(validator_two, validator_three, object)
validator.valid?
validator.errors.detailed_messages

Defined Under Namespace

Modules: Errors, List, Object, Validator Classes: NestedValidator, Railtie, ValidatorsList

Constant Summary collapse

VERSION =
'0.1.2'.freeze