0.0
No commit activity in last 3 years
No release in over 3 years
This gem extends the functionality of Rails' ActiveModel::Errors with a #by_type method that returns a hash of error messages scoped by attribute and type.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.0
~> 1.8.7
~> 3.12
~> 2.8.0
 Project Readme

ActiveModel::Errors #by_type¶ ↑

Use #by_type on an instance of ActiveModel::Errors (presumably in Rails) to retrieve a hash of error messages scoped by attribute and type. Empower your server-sent, serialized form/record validation messages to play nicely with data-binding JS frameworks. Get more granular with your validation UIs.

Installation¶ ↑

Add the following to your Gemfile and bundle install.

gem 'ames_by_type'

Usage¶ ↑

When an error message is added to an instance of ActiveModel::Errors, we add said error message (organized by attribute and message type) to a messages_by_type hash. We can retrieve this hash as it exists or with full messages (by keyword argument, shown below).

zebra.errors.add(:name, :blank)
zebra.errors.add(:name, :too_short, count: 2)
zebra.errors.by_type
# =>  {
        name: {
          blank: "can't be blank",
          too_short: "is too short (minimum is 2 characters)"
        }
      }
zebra.errors.by_type(full_messages: true)
# =>  {
        name: {
            blank: "Name can't be blank",
            too_short: "Name is too short (minimum is 2 characters)"
        }
      }

In a Rails controller action:

...
def create
  @zebra = Zebra.new(zebra_params)
  if @zebra.save
    render json: @zebra
  else
    render json: @zebra.errors.by_type
  end
end
...

Learn how to set up translations for your ActiveRecord models (including error messages) here.

Copyright © 2014 Travis Loncar.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.