Skip to content

Commit f0caa54

Browse files
author
Yevhenii Kurtov
committed
Add ability to specify validation context
In some cases, users want to run API-specific validations. This commit allows to pass a validation context to the JSONAPI::Resource#_super method
1 parent 2d7e38b commit f0caa54

3 files changed

Lines changed: 29 additions & 3 deletions

File tree

lib/jsonapi/resource.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def save
182182
# return :accepted
183183
# end
184184
# ```
185-
def _save
186-
unless @model.valid?
185+
def _save(validation_context = nil)
186+
unless @model.valid?(validation_context)
187187
fail JSONAPI::Exceptions::ValidationErrors.new(self)
188188
end
189189

test/fixtures/active_record.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ def destroy
406406
$breed_data.remove(@id)
407407
end
408408

409-
def valid?
409+
def valid?(context = nil)
410410
@errors.clear
411411
if name.is_a?(String) && name.length > 0
412412
return true

test/unit/resource/resource_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,28 @@ def do_some_after_save_stuff
1818
end
1919
end
2020

21+
class PostWithCustomValidationContext < ActiveRecord::Base
22+
self.table_name = 'posts'
23+
validate :api_specific_check, on: :json_api_create
24+
25+
def api_specific_check
26+
errors[:base] << 'Record is invalid'
27+
end
28+
end
29+
2130
class ArticleWithBadAfterSaveResource < JSONAPI::Resource
2231
model_name 'PostWithBadAfterSave'
2332
attribute :title
2433
end
2534

35+
class ArticleWithCustomValidationContextResource < JSONAPI::Resource
36+
model_name 'PostWithCustomValidationContext'
37+
attribute :title
38+
def _save
39+
super(:json_api_create)
40+
end
41+
end
42+
2643
class NoMatchResource < JSONAPI::Resource
2744
end
2845

@@ -557,4 +574,13 @@ def test_resource_for_model_use_hint
557574
resource_model = SpecialPersonResource.records({}).first # simulate a find
558575
assert_equal(SpecialPersonResource, SpecialPersonResource.resource_for_model(resource_model))
559576
end
577+
578+
def test_resource_performs_validations_in_custom_context
579+
post = PostWithCustomValidationContext.find(1)
580+
post_resource = ArticleWithCustomValidationContextResource.new(post, nil)
581+
err = assert_raises JSONAPI::Exceptions::ValidationErrors do
582+
post_resource._save
583+
end
584+
assert_equal(err.error_messages[:base], ['Record is invalid'])
585+
end
560586
end

0 commit comments

Comments
 (0)