diff --git a/lib/dry/schema/messages/i18n.rb b/lib/dry/schema/messages/i18n.rb index 49e9be54..7f9d8972 100644 --- a/lib/dry/schema/messages/i18n.rb +++ b/lib/dry/schema/messages/i18n.rb @@ -32,7 +32,8 @@ def initialize def get(key, options = EMPTY_HASH) return unless key - result = t.(key, locale: options.fetch(:locale, default_locale)) + options[:locale] ||= default_locale + result = t.(key, **options) if result.is_a?(Hash) text = result[:text] @@ -112,7 +113,10 @@ def interpolate(key, options, **data) resolved_key = key?(text_key, opts) ? text_key : key - t.(resolved_key, **opts) + result = t.(resolved_key, **opts) + return result unless result.is_a?(Hash) + + result[:text] end private diff --git a/spec/integration/messages/i18n_spec.rb b/spec/integration/messages/i18n_spec.rb index ec2a2fca..13b6f69b 100644 --- a/spec/integration/messages/i18n_spec.rb +++ b/spec/integration/messages/i18n_spec.rb @@ -188,6 +188,17 @@ def store_errors(**errors) expect(meta).to eql({}) end + it "can use a proc returning hash for a message" do + store_errors( + predicate_proc: ->(_path, **opts) { {text: opts[:text], code: 123, name: opts[:name]} } + ) + + template, meta = messages[:predicate_proc, path: :path, text: "text", name: "abc"] + + expect(template.()).to eql("text") + expect(meta).to eql({code: 123, name: "abc"}) + end + context "with meta-data" do it "finds the meta-data" do store_errors( @@ -203,6 +214,26 @@ def store_errors(**errors) expect(meta).to eql(code: 123) end end + + context "with meta-data and arg type" do + it "returns a template for a specific rule, meta and default arg type" do + store_errors( + predicate_with_meta: { + arg: { + default: { + text: "text %{arg}", + code: 123 + } + } + } + ) + + template, meta = messages[:predicate_with_meta, path: :pages, locale: :en] + + expect(template.(arg: "some arg")).to eql("text some arg") + expect(meta).to eq({code: 123}) + end + end end context "with dynamic locale" do