Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

apiable_model_errors

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

apiable_model_errors

  • 1.0.0
  • Rubygems
  • Socket score

Version published
Maintainers
1
Created
Source

APIable Model Errors

ActiveModel provides a great framework for handling validations for models. It easily allows you to add any validation message to any attribute however these arbitary strings aren't very helpful if you want to deliver validation errors to APIs. API developers don't want to see Number is too long (maximum is 5 characters), they would much rather see something they can handle programatically like too_long or blank.

This gem extends the ActiveModel::Errors class to allow for a more API-friendly hash of errors to be returned.

Installation

gem "apiable_model_errors"

Usage

Once you've installed the gems, you can call the to_api_hash method on any ActiveModel::Errors object.

user = User.new(params)
unless user.valid?
  user.errors.to_api_hash
end

Example Output

When using this you'll receive a ruby hash however you can easily convert this into JSON by calling to_json on the hash.

{
  "name":[
    {
      "code":"too_long",
      "message":"is too long (maximum is 4 characters)",
      "options":{
        "count":4
      }
    }
  ]
}

As you can see you'll receive the code, the actual translated message from ActiveModel and any options.

has_message?

In addition to provide the to_api_hash method, we also provide a method called has_message? which allows you to determine if a message exists for a given attribute. This is similar to the added? however does not require that you provide all options to see if a message has been added.

# See if there are any :too_long messages on the name attribute
user.errors.has_message?(:name, :too_long)
# See if there are any :too_long messages on the name attribute
# with the options provided.
user.errors.has_message?(:name, :too_long, :count => 4)
# See if there are any :blank messages on the name attribute
user.errors.has_message?(:name, :blank)

FAQs

Package last updated on 06 Feb 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc