A platform for community discussion. Free, open, simple.
DEV: Handle nested attributes in contracts (#36348)
Loïc Guitaut89be127ced84
diff --git a/lib/service/base.rb b/lib/service/base.rbindex 6cc4690e9b6..48bfc0a4799 100644--- a/lib/service/base.rb+++ b/lib/service/base.rb@@ -245,10 +245,7 @@ module Servicedef run_stepcontract =- class_name.new(- **default_values.merge(context[:params].slice(*attributes)),- options: context[:options],- )+ class_name.new(**default_values.merge(context[:params]), options: context[:options])context[contract_name] = contractif contract.invalid?context[result_key].fail(errors: contract.errors, parameters: contract.raw_attributes)@@ -271,11 +268,7 @@ module Servicedef default_valuesreturn {} unless default_values_frommodel = context[default_values_from]- (model.try(:attributes).try(:with_indifferent_access) || model).slice(*attributes)- end-- def attributes- class_name.attribute_names.map(&:to_sym)+ model.try(:attributes).try(:with_indifferent_access) || modelendenddiff --git a/lib/service/contract_base.rb b/lib/service/contract_base.rbindex 698d4b3d383..bdacc366460 100644--- a/lib/service/contract_base.rb+++ b/lib/service/contract_base.rb@@ -8,8 +8,29 @@ class Service::ContractBasedelegate :slice, :merge, to: :to_hash+ class << self+ def attribute(name, cast_type = nil, **options, &block)+ return super(name, cast_type, **options) unless block_given?++ nested_contract_class =+ Class.new(Service::ContractBase) do+ define_singleton_method(:name) { "#{name}_contract".classify }+ class_eval(&block)+ end+ super(+ name,+ Service::NestedContractType.new(+ contract_class: nested_contract_class,+ nested_type: cast_type || :hash,+ ),+ **options,+ )+ end+ end+def initialize(*args, options: nil, **kwargs)@__options__ = options+ kwargs.deep_symbolize_keys!.slice!(*self.class.attribute_names.map(&:to_sym))super(*args, **kwargs)end@@ -18,10 +39,45 @@ class Service::ContractBaseenddef to_hash- attributes.symbolize_keys+ attributes.symbolize_keys.deep_transform_values do+ _1.is_a?(Service::ContractBase) ? _1.to_hash : _1+ endenddef raw_attributes@attributes.values_before_type_castend++ def valid?(context = nil)+ [super, nested_attributes_valid?].all?+ end++ private++ def nested_attributes_valid?+ nested_attributes.map(&method(:validate_nested)).all?+ end++ def nested_attributes+ @attributes.each_value.select { _1.type.is_a?(Service::NestedContractType) && _1.value }+ end++ def validate_nested(attribute)+ Array+ .wrap(attribute.value)+ .map+ .with_index do |contract, index|+ next true if contract.valid?+ import_nested_errors(contract, attribute, index)+ false+ end+ .all?+ end++ def import_nested_errors(contract, attribute, index)+ array_index = "[#{index}]" if attribute.value.is_a?(Array)+ contract.errors.each do |error|+ errors.import(error, attribute: :"#{attribute.name}#{array_index}.#{error.attribute}")+ end+ endenddiff --git a/lib/service/nested_contract_type.rb b/lib/service/nested_contract_type.rbnew file mode 100644index 00000000000..952dc786870--- /dev/null+++ b/lib/service/nested_contract_type.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++module Service+ class NestedContractType < ActiveModel::Type::Value+ attr_reader :contract_class, :nested_type++ def initialize(contract_class:, nested_type: :hash)+ super()+ @contract_class = contract_class+ @nested_type = nested_type.to_s.inquiry+ end++ def cast_value(value)+ case value+ when ->(*) { nested_type.hash? }+ cast_hash(value)+ when ->(*) { nested_type.array? && value.is_a?(Array) }+ value.filter_map(&method(:cast_hash))+ else+ nil+ end+ end++ private++ def cast_hash(value)+ return unless value.is_a?(Hash)+ contract_class.new(**value)+ end+ end+enddiff --git a/spec/lib/service/contract_base_spec.rb b/spec/lib/service/contract_base_spec.rbnew file mode 100644index 00000000000..26cfd9f5796--- /dev/null+++ b/spec/lib/service/contract_base_spec.rb@@ -0,0 +1,204 @@+# frozen_string_literal: true++RSpec.describe Service::ContractBase, type: :model do+ subject(:contract) { contract_class.new(params) }++ describe "Nested attributes" do+ let(:contract_class) do+ Class.new(described_class) do+ def self.name = "TestContract"++ attribute :channel_id, :integer++ attribute :record, :hash do+ attribute :id, :integer+ attribute :created_at, :datetime+ attribute :enabled, :boolean+ end++ attribute :user do # without an explicit type, it defaults to :hash+ attribute :username, :string+ attribute :age, :integer++ validates :username, presence: true+ end++ attribute :records, :array do+ attribute :name++ validates :name, presence: true+ end++ validates :channel_id, :user, presence: true+ end+ end+ let(:params) do+ {+ channel_id: 123,+ record: {+ id: 1,+ created_at: "2025-12-25 00:00",+ enabled: true,+ },+ user: {+ username: "alice",+ age: 30,+ },+ records: [{ name: "first" }, { name: "second" }],+ }+ end+ let(:created_at) { Time.zone.parse("2025-12-25 00:00") }++ describe "Validations" do+ it { is_expected.to validate_presence_of(:channel_id) }+ it { is_expected.to validate_presence_of(:user) }++ context "when user is defined" do+ subject(:user_contract) { contract.user }++ it { is_expected.to validate_presence_of(:username) }++ context "when user has errors" do+ before { params[:user].delete(:username) }++ it "marks the main contract as invalid" do+ expect(contract).to be_invalid+ expect(contract.errors).to include(:"user.username")+ end+ end+ end++ context "when records is defined" do+ subject(:records_contracts) { contract.records }++ it { is_expected.to all validate_presence_of(:name) }++ context "when records has errors" do+ before { params[:records][1].delete(:name) }++ it "marks the main contract as invalid" do+ expect(contract).to be_invalid+ expect(contract.errors).to include(:"records[1].name")+ end+ end+ end+ end++ it "casts nested attributes to contract objects" do+ expect(contract).to have_attributes(+ record: a_kind_of(Service::ContractBase),+ user: a_kind_of(Service::ContractBase),+ records: all(a_kind_of(Service::ContractBase)),+ )+ end++ it "exposes nested attribute values" do+ expect(contract).to have_attributes(+ record: an_object_having_attributes(id: 1, enabled: true, created_at:),+ user: an_object_having_attributes(username: "alice", age: 30),+ records:+ a_collection_containing_exactly(+ an_object_having_attributes(name: "first"),+ an_object_having_attributes(name: "second"),+ ),+ )+ end++ it "converts to a nested hash" do+ expect(contract.to_hash).to include(+ channel_id: 123,+ record: {+ id: 1,+ enabled: true,+ created_at:,+ },+ user: {+ username: "alice",+ age: 30,+ },+ records: [{ name: "first" }, { name: "second" }],+ )+ end++ context "with multiple levels of nesting" do+ let(:contract_class) do+ Class.new(described_class) do+ def self.name = "TestContract"++ attribute :data do+ attribute :nested do+ attribute :value, :string++ validates :value, presence: true+ end+ end++ attribute :items, :array do+ attribute :name, :string++ attribute :nested, :array do+ attribute :value, :string++ validates :value, presence: true+ end++ validates :name, presence: true+ end+ end+ end+ let(:params) do+ {+ data: {+ nested: {+ value: "deep",+ },+ },+ items: [{ name: "item 1", nested: [{ value: "deep" }] }],+ }+ end++ it { is_expected.to be_valid }++ it "handles deeply nested structures" do+ expect(contract.data.nested.value).to eq("deep")+ expect(contract.items[0].nested[0].value).to eq("deep")+ end++ it "properly converts to a hash" do+ expect(contract.to_hash).to include(+ data: {+ nested: {+ value: "deep",+ },+ },+ items: [{ name: "item 1", nested: [{ value: "deep" }] }],+ )+ end++ context "when there are errors at several levels" do+ let(:params) do+ {+ data: {+ nested: {+ value: "deep",+ },+ },+ items: [+ { name: "item 1", nested: [{ value: "" }] },+ { nested: [{ value: "1" }, { value: "" }] },+ ],+ }+ end++ it "reports all the proper errors" do+ expect(contract).to be_invalid+ expect(contract.errors).to include(+ :"items[0].nested[0].value",+ :"items[1].name",+ :"items[1].nested[1].value",+ )+ end+ end+ end+ end+enddiff --git a/spec/lib/service/nested_contract_type_spec.rb b/spec/lib/service/nested_contract_type_spec.rbnew file mode 100644index 00000000000..0f4311d939c--- /dev/null+++ b/spec/lib/service/nested_contract_type_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++RSpec.describe Service::NestedContractType do+ subject(:type) { described_class.new(contract_class:, nested_type:) }++ let(:contract_class) do+ Class.new(Service::ContractBase) do+ attribute :id, :integer+ attribute :name, :symbol+ end+ end++ describe "#cast" do+ subject(:casted_value) { type.cast(value) }++ context "when 'nested_type' is :hash" do+ let(:nested_type) { :hash }++ context "when 'value' is a hash" do+ let(:value) { { id: "1", name: "symbol" } }++ it "converts the hash to a contract" do+ expect(casted_value).to be_a(contract_class)+ expect(casted_value).to have_attributes(id: 1, name: :symbol)+ end+ end++ context "when 'value' is an array" do+ let(:value) { [{ id: "1", name: "symbol" }] }++ it "returns nothing" do+ expect(casted_value).to be_nil+ end+ end++ context "when 'value' is something else" do+ let(:value) { "value" }++ it "returns nothing" do+ expect(casted_value).to be_nil+ end+ end+ end++ context "when 'nested_type' is :array" do+ let(:nested_type) { :array }++ context "when 'value' is a hash" do+ let(:value) { { id: "1", name: "symbol" } }++ it "returns nothing" do+ expect(casted_value).to be_nil+ end+ end++ context "when 'value' is an array" do+ let(:value) { [{ id: "1", name: "symbol" }, { id: "2", name: "other_symbol" }, ""] }++ it "converts the hashes from the array to an array of contracts" do+ expect(casted_value).to contain_exactly(+ an_object_having_attributes(id: 1, name: :symbol),+ an_object_having_attributes(id: 2, name: :other_symbol),+ )+ end+ end++ context "when 'value' is something else" do+ let(:value) { "value" }++ it "returns nothing" do+ expect(casted_value).to be_nil+ end+ end+ end+ end+end