Skip to content

Commit

Permalink
Support proc as source option
Browse files Browse the repository at this point in the history
  • Loading branch information
mkon committed Jun 2, 2023
1 parent f4954f0 commit 4969749
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
11 changes: 8 additions & 3 deletions lib/invalid_model/each_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,15 @@ def meta
end

def source
return @options[:source] if @options.key?(:source)
return if attribute == :base
if @options[:source].respond_to?(:call)
@options[:source].call resource, error
elsif @options.key?(:source)
@options[:source]
else
return if attribute == :base

{pointer: "/data/attributes/#{attribute}"}
{pointer: "/data/attributes/#{attribute}"}
end
end

def status
Expand Down
25 changes: 23 additions & 2 deletions spec/invalid_model/serializer_spec.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# require 'invalid_model/serializer'

RSpec.describe InvalidModel::Serializer do
subject(:hash) { described_class.new(model.tap(&:valid?)).serializable_hash }
subject(:hash) { described_class.new(model.tap(&:valid?), options).serializable_hash }

let(:json) { MultiJson.dump(hash) }
let(:options) { {} }

context 'when the model multiple errors' do
context 'when the model has multiple errors' do
let(:model) { DummyModel.new(code: '?', size: 'wrong') }

it 'has 4 errors' do
Expand Down Expand Up @@ -81,6 +82,26 @@
JSON
).at_path('errors')
end

context 'when injecting a custom source' do
let(:options) { {source: ->(_m, e) { {'pointer' => "/#{e.attribute}"} }} }

it 'renders correct json' do
expect(json).to be_json_eql(<<~JSON).at_path('errors/0')
{
"code": "validation_error/invalid",
"detail": "Code is invalid",
"meta": {
"value": "?"
},
"source": {
"pointer": "/code"
},
"status": "400"
}
JSON
end
end
end

context 'when the model has a custom error' do
Expand Down

0 comments on commit 4969749

Please sign in to comment.