Rosebud
Rails API parameter validation
Installation
Add this line to your application's Gemfile:
gem 'rosebud'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rosebud
Usage
Getting Started
Just include Rosebud
in your Rails controller.
class Api::V1::SomeController < Api::V1::ApplicationController
include Rosebud
end
Validating Parameters
To validate parameters specify a params
block and choose whether the params are required or optional.
class Api::V1::SomeController < Api::V1::ApplicationController
include Rosebud
params do
requires :name
optional :phone_number, regex: /\d{10}/, default: '5555555555'
end
...
end
It's also possible to define validations for a specific action.
class Api::V1::SomeController < Api::V1::ApplicationController
include Rosebud
params :create do
...
end
def create
...
end
end
Rendering Errors
When a parameter error is raised a JSON response will be rendered.
{
"error": "missing_parameter",
"description": "missing parameter: name"
}
Custom Validators
Currently the only validators that ship with Rosebud are presence
, regex
and type
. If you need other validators you can create your own.
class MyLengthValidator < Rosebud::Validator
def validate_param(name, value, )
if value.length <=
error!(:length, param: name, length: value.length, max_length: )
end
end
end
Rosebud::Validations.register_validator!(:length, MyLengthValidator)
Rosebud uses the Errawr::Rails gem to raise and render localised errors. Add your custom error message to your locale file.
en:
errawr:
length:
message: %{length} characters is too long for %{param}, should be less than or equal to %{max_length}
http_status: 400
metadata:
additional_info: Kick him in the shins!
Add a validation using your custom validator:
class Api::V1::SomeController < Api::V1::ApplicationController
include Rosebud
params :create do
requires :name, length: 2
end
def create
...
end
end
The following error will be rendered for the name
parameter when provided with a value of abc
:
{
"error": "length",
"description": "3 characters is too long for name, should be less than or equal to 2",
"additional_info": "Kcik him in the shins!"
}
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
Credits
Rosebud is maintained and funded by Sticksnleaves
Thanks to all of our contributors