A platform for community discussion. Free, open, simple.
DEV: Preserve nested model defaults in service contracts
Loïc Guitaut875b2a384d17
diff --git a/docs/developer-guides/docs/03-code-internals/20-service-objects.md b/docs/developer-guides/docs/03-code-internals/20-service-objects.mdindex fe53007b6ea..1f2c55071d3 100644--- a/docs/developer-guides/docs/03-code-internals/20-service-objects.md+++ b/docs/developer-guides/docs/03-code-internals/20-service-objects.md@@ -336,6 +336,12 @@ This matcher expects the service to succeed.This step declares the use of a contract to validate input parameters. Parameters provided to the service will be passed to the contract if their name matches the attributes defined in the contract.+With `default_values_from`, nested hashes are merged recursively. Supplied values override model values, including `nil`, `false`, and `0`. An empty hash keeps the defaults at that level. A supplied array replaces the whole model array; an empty array clears it.++For example, model values `{ dimensions: { width: 640, height: 480 }, tags: ["draft"] }` combined with params `{ dimensions: { width: 800 }, tags: [] }` produce `{ dimensions: { width: 800, height: 480 }, tags: [] }` before contract validation.++String and symbol keys are treated alike at every level. Combining defaults and inputs does not modify their hashes or arrays. Coercion and validation still run on the resulting values.+Under the hood, a class for the contract will be automatically created, allowing easy testing. The default contract will result in `Contract`, otherwise it will prepend the name used for the contract (for `params(:user_avatar)`, this will give `UserAvatarContract`).If the contract is invalid, it will stop the execution of the service. Its result object can be inspected by accessing the `result.contract.<name>` key of the main result object. The contract result object exposes two keys:diff --git a/lib/service/base/contract_step.rb b/lib/service/base/contract_step.rbindex b75eaf168b3..49401732b27 100644--- a/lib/service/base/contract_step.rb+++ b/lib/service/base/contract_step.rb@@ -13,7 +13,7 @@ module Servicedef run_stepcontract =- class_name.new(**default_values.merge(context[:params]), options: context[:options])+ class_name.new(**default_values.deep_merge(context[:params]), options: context[:options])context[contract_name] = contractif contract.invalid?context[result_key].fail(errors: contract.errors, parameters: contract.raw_attributes)@@ -36,7 +36,7 @@ module Servicedef default_valuesreturn {} unless default_values_frommodel = context[default_values_from]- model.try(:attributes).try(:with_indifferent_access) || model+ (model.try(:attributes) || model).with_indifferent_accessendendenddiff --git a/lib/service/contract_base.rb b/lib/service/contract_base.rbindex 3c1633d4326..a6066219593 100644--- a/lib/service/contract_base.rb+++ b/lib/service/contract_base.rb@@ -30,8 +30,7 @@ class Service::ContractBasedef initialize(*args, options: nil, **kwargs)@__options__ = options- kwargs.deep_symbolize_keys!.slice!(*self.class.attribute_names.map(&:to_sym))- super(*args, **kwargs)+ super(*args, **kwargs.deep_symbolize_keys.slice(*self.class.attribute_names.map(&:to_sym)))enddef optionsdiff --git a/spec/lib/service/contract_base_spec.rb b/spec/lib/service/contract_base_spec.rbindex 71503e26730..6a0a5a97a7d 100644--- a/spec/lib/service/contract_base_spec.rb+++ b/spec/lib/service/contract_base_spec.rb@@ -49,6 +49,24 @@ RSpec.describe Service::ContractBase, type: :model doendlet(:created_at) { Time.zone.parse("2025-12-25 00:00") }+ context "when nested containers are frozen" do+ subject(:contract) { contract_class.new(**params) }++ let(:params) { super().deep_stringify_keys }++ before do+ params["record"].freeze+ params["user"].freeze+ params["records"].each(&:freeze)+ params["records"].freeze+ params.freeze+ end++ it "accepts the parameters" do+ expect(contract).to be_valid+ end+ end+describe "Validations" doit { is_expected.to validate_presence_of(:channel_id) }it { is_expected.to validate_presence_of(:user) }diff --git a/spec/lib/service_spec.rb b/spec/lib/service_spec.rbindex 2cfd3641834..01ffa7beaf7 100644--- a/spec/lib/service_spec.rb+++ b/spec/lib/service_spec.rb@@ -173,18 +173,214 @@ RSpec.describe Service doenddescribe "Using values from a model" do+ let(:args) { super().merge(params:, stored_model:) }+ let(:params) { {} }+ let(:stored_model) { defaults }+ let(:defaults) { { id: 1, name: "John" } }+before doservice_class.class_eval do- model :user+ model- params(default_values_from: :user) do+ params(default_values_from: :model) doattribute :id, :integerattribute :name, :stringattribute :groups, :array, default: -> { [] }end- def fetch_user- { id: 1, name: "John" }+ def fetch_model(stored_model:)+ stored_model+ end+ end+ end++ context "when the model has nested attributes" do+ let(:params) { super().merge(dimensions: { width: 800, crop: { x: 10 } }) }+ let(:defaults) do+ super().merge(+ caption: "Original",+ enabled: true,+ dimensions: {+ "width" => 640,+ "height" => 480,+ "crop" => {+ "x" => 20,+ "y" => 30,+ },+ },+ layers: [{ "width" => 100, "height" => 200 }],+ )+ end++ before do+ service_class::Contract.class_eval do+ attribute :caption, :string+ attribute :enabled, :boolean++ attribute :dimensions, :hash do+ attribute :width, :integer+ attribute :height, :integer++ attribute :crop, :hash do+ attribute :x, :integer+ attribute :y, :integer+ end++ validates :width, :height, presence: true+ end++ attribute :layers, :array do+ attribute :width, :integer+ attribute :height, :integer+ end++ validates :dimensions, presence: true+ end+ end++ context "when nested values are omitted" do+ it "fills omitted keys at each level" do+ expect(result.params.dimensions.to_hash).to eq(+ width: 800,+ height: 480,+ crop: {+ x: 10,+ y: 30,+ },+ )+ end++ it "validates the completed input" do+ expect(result).to run_successfully+ end++ it "preserves an omitted array" do+ expect(result.params.to_hash[:layers]).to eq([{ width: 100, height: 200 }])+ end++ it "leaves the model defaults unchanged" do+ expect { result }.not_to change { defaults.deep_dup }+ end+ end++ context "when the input has string keys" do+ let(:params) { { "dimensions" => { "width" => 800, "crop" => { "x" => 10 } } } }++ it "leaves the supplied input unchanged" do+ expect { result }.not_to change { params.deep_dup }+ end++ it "combines string and symbol keys" do+ expect(result.params.dimensions.to_hash).to eq(+ width: 800,+ height: 480,+ crop: {+ x: 10,+ y: 30,+ },+ )+ end+ end++ context "when the model exposes its attributes" do+ let(:stored_model) { Struct.new(:attributes).new(defaults) }++ it "fills omitted keys from model attributes" do+ expect(result.params.dimensions.to_hash).to eq(+ width: 800,+ height: 480,+ crop: {+ x: 10,+ y: 30,+ },+ )+ end+ end++ context "when an empty hash is supplied" do+ let(:params) { { dimensions: {} } }++ it "preserves the nested defaults" do+ expect(result.params.dimensions.to_hash).to eq(+ width: 640,+ height: 480,+ crop: {+ x: 20,+ y: 30,+ },+ )+ end+ end++ context "when explicit nil and falsy values are supplied" do+ let(:params) { { caption: nil, enabled: false, dimensions: { width: 0 } } }++ it "uses the supplied values" do+ expect(result.params.to_hash).to include(+ caption: nil,+ enabled: false,+ dimensions: {+ width: 0,+ height: 480,+ crop: {+ x: 20,+ y: 30,+ },+ },+ )+ end+ end++ context "when a nested hash is explicitly cleared" do+ let(:params) { { dimensions: nil } }++ it "keeps the supplied nil" do+ expect(result.params.dimensions).to be_nil+ end++ it "validates the supplied nil" do+ expect(result).to fail_a_contract+ end+ end++ context "when a nested hash has an invalid shape" do+ let(:params) { { dimensions: "invalid" } }++ it "rejects the input" do+ expect(result).to fail_a_contract+ end+ end++ context "when an array is supplied" do+ let(:params) { { layers: [{ width: 300 }] } }++ it "replaces the array without inheriting elements or their fields" do+ expect(result.params.to_hash[:layers]).to eq([{ width: 300, height: nil }])+ end+ end++ context "when an empty array is supplied" do+ let(:params) { { layers: [] } }++ it "clears the array" do+ expect(result.params.layers).to be_empty+ end+ end++ context "when a named contract follows the default contract" do+ before do+ service_class.class_eval do+ params(:resize) do+ attribute :dimensions, :hash do+ attribute :width, :integer+ attribute :height, :integer+ end+ end+ end+ end++ it "passes the completed parameters to the named contract" do+ expect(result.resize_contract.dimensions.to_hash).to eq(width: 800, height: 480)endendend