Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mkon/invalid_model-serializer
Serialize models with validation errors to json-api errors.
https://github.com/mkon/invalid_model-serializer
json-api rails ruby
Last synced: 8 days ago
JSON representation
Serialize models with validation errors to json-api errors.
- Host: GitHub
- URL: https://github.com/mkon/invalid_model-serializer
- Owner: mkon
- License: mit
- Created: 2019-02-17T13:01:52.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2024-08-12T19:20:45.000Z (3 months ago)
- Last Synced: 2024-10-20T07:27:37.361Z (16 days ago)
- Topics: json-api, rails, ruby
- Language: Ruby
- Homepage:
- Size: 60.5 KB
- Stars: 2
- Watchers: 2
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# InvalidModel Serializer
You are using one of the many ruby `json_api` serializer gems like `active_model_serializers` or `fast_jsonapi`, but are not satisfied with the rendering of validation errors?
This gem is trying to fit this gap.
## Usage
Add the gem to your Gemfile
```ruby
gem 'invalid_model-serializer'
```To generate a `json-api` compliant error hash simply call
```ruby
InvalidModel::Serializer.new(invalid_model).serializable_hash
```Which should parse your `ActiveModel` compatible errors and produce something like:
```json
{
"errors": [
{
"code": "validation_error/too_short",
"detail": "Name is too short (minimum is 6 characters)",
"meta": {
"count": 6
},
"source": {
"pointer": "/data/attributes/name"
},
"status": "400"
}
]
}
```### Rails
In a rails controller you could for example use:
```ruby
def create
...
if @record.save
head :no_content
else
render json: InvalidModel::Serializer.new(@record).serializable_hash, status: :bad_request
end
end
```### Options
You can pass options to the serializer as 2nd argument. The following keys are supported:
* `code_format`: Override the default format. This string will be passed through a `format` method so you can use some placeholders like `type` and `attribute`.
* `status`: Set a different status, default is `400`
* `each_serializer`: Use your own serializer for error objects.### Configuration
Additionally you can set `code_format` and `status` globally via:
```ruby
InvalidModel::Serializer.configure do |config|
config.default_code_format = 'validation_error/%{model}.%{attribute}.%{type}'
config.default_status = '422'
end
```