Skip to content

A platform for community discussion. Free, open, simple.

DEV: Forward options to nested contracts (#42786)

Loïc Guitaut4cf8388877dc
diff --git a/lib/service/contract_base.rb b/lib/service/contract_base.rb
index b4f3241634f..3c1633d4326 100644
--- a/lib/service/contract_base.rb
+++ b/lib/service/contract_base.rb
@@ -52,6 +52,12 @@ class Service::ContractBase
[super, nested_attributes_valid?].all?
end
+ protected
+
+ def options=(options)
+ @__options__ = options
+ end
+
private
def nested_attributes_valid?
@@ -67,6 +73,7 @@ class Service::ContractBase
.wrap(attribute.value)
.map
.with_index do |contract, index|
+ contract.options = options
next true if contract.valid?
import_nested_errors(contract, attribute, index)
false
diff --git a/spec/lib/service/contract_base_spec.rb b/spec/lib/service/contract_base_spec.rb
index 26cfd9f5796..71503e26730 100644
--- a/spec/lib/service/contract_base_spec.rb
+++ b/spec/lib/service/contract_base_spec.rb
@@ -84,6 +84,20 @@ RSpec.describe Service::ContractBase, type: :model do
end
end
+ context "when the main contract has options" do
+ subject(:contract) { contract_class.new(params, options: { locale: "fr" }) }
+
+ it "provides them to a nested contract" do
+ contract.valid?
+ expect(contract.record.options).to include(locale: "fr")
+ end
+
+ it "provides them to a contract nested inside a nested one" do
+ contract.valid?
+ expect(contract.records.map(&:options)).to all(include(locale: "fr"))
+ end
+ end
+
it "casts nested attributes to contract objects" do
expect(contract).to have_attributes(
record: a_kind_of(Service::ContractBase),