Skip to content

Commit

Permalink
Propagate translation options on nested error to parent when validate…
Browse files Browse the repository at this point in the history
…s_associated
  • Loading branch information
nicklandgrebe committed Feb 18, 2017
1 parent 4155f49 commit 2178fbd
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 8 deletions.
10 changes: 4 additions & 6 deletions lib/caprese/error.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
# TODO: Remove in favor of Rails 5 error details and dynamically setting i18n_scope
module Caprese
class Error < StandardError
attr_reader :field
attr_reader :code

attr_reader :header
attr_reader :field, :code, :header

# Initializes a new error
#
Expand Down Expand Up @@ -103,15 +100,16 @@ def as_json
}
end

private

# Adds field and capitalized Field title to the translation params for every error
# and returns them
#
# @return [Hash] the full translation params of the error
def t
@t.merge(field: @field, field_title: @field.to_s.titleize)
end

private

# Checks whether or not a translation exists
#
# @param [String] key the I18n translation key
Expand Down
2 changes: 1 addition & 1 deletion lib/caprese/record/associated_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def validate_each(record, attribute, value)
Array(value).reject { |r| r.marked_for_destruction? || r.valid? }.each do |invalid_record|
invalid_record.errors.to_a.each do |error|
field_name = error.field ? "#{attribute}.#{error.field}" : attribute
record.errors.add(field_name, error.code, options.merge(value: invalid_record))
record.errors.add(field_name, error.code, { t: error.t }.merge(value: invalid_record))
end
end
end
Expand Down
10 changes: 9 additions & 1 deletion spec/dummy/app/models/rating.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
class Rating < ApplicationRecord
belongs_to :comment

validates_presence_of :value
validate :value_is_correct

private

def value_is_correct
return if value

errors.add(:value, :invalid, t: { custom_val: '123' })
end
end
8 changes: 8 additions & 0 deletions spec/dummy/config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,11 @@

en:
hello: "Hello world"
api:
v1:
errors:
models:
comment:
rating:
value:
invalid: Test value %{custom_val}
4 changes: 4 additions & 0 deletions spec/persistence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,10 @@
it 'correctly points to the attribute that caused the error' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/rating/data/attributes/value')
end

it 'propagates nested error options' do
expect(json['errors'][0]['detail']).to eq(I18n.t('api.v1.errors.models.comment.rating.value.invalid', custom_val: '123'))
end
end
end
end
Expand Down

0 comments on commit 2178fbd

Please sign in to comment.