Class: Hanami::Action::Params::Errors

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
gems/gems/hanami-controller-2.1.0/lib/hanami/action/params.rb

Overview

Params errors

Since:

  • 1.1.0

Instance Method Summary collapse

Instance Method Details

#add(*args) ⇒ Object

Add an error to the param validations

This has a semantic similar to Hash#dig where you use a set of keys to get a nested value, here you use a set of keys to set a nested value.

Examples:

Basic usage

require "hanami/controller"

class MyAction < Hanami::Action
  params do
    required(:book).schema do
      required(:isbn).filled(:str?)
    end
  end

  def handle(req, res)
    # 1. Don't try to save the record if the params aren't valid
    return unless req.params.valid?

    BookRepository.new.create(req.params[:book])
  rescue Hanami::Model::UniqueConstraintViolationError
    # 2. Add an error in case the record wasn't unique
    req.params.errors.add(:book, :isbn, "is not unique")
  end
end

Invalid argument

require "hanami/controller"

class MyAction < Hanami::Action
  params do
    required(:book).schema do
      required(:title).filled(:str?)
    end
  end

  def handle(req, *)
    puts req.params.to_h   # => {}
    puts req.params.valid? # => false
    puts req.params.error_messages # => ["Book is missing"]
    puts req.params.errors         # => {:book=>["is missing"]}

    req.params.errors.add(:book, :isbn, "is not unique") # => ArgumentError
  end
end

Parameters:

  • args (Array<Symbol, String>)

    an array of arguments: the last one is the message to add (String), while the beginning of the array is made of keys to reach the attribute.

Raises:

  • (ArgumentError)

    when try to add a message for a key that is already filled with incompatible message type. This usually happens with nested attributes: if you have a :book schema and the input doesn’t include data for :book, the messages will be ["is missing"]. In that case you can’t add an error for a key nested under :book.

Since:

  • 1.1.0

def add(*args)
  *keys, key, error = args
  _nested_attribute(keys, key) << error
rescue TypeError
  raise ArgumentError.new("Can't add #{args.map(&:inspect).join(', ')} to #{inspect}")
end