Skip to content

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

DEV: Reuse writable resource declarations in service contracts

Loïc Guitaut46b3e2239ebd
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.md
index 1f2c55071d3..950de259f13 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
@@ -325,17 +325,33 @@ This matcher expects the service to succeed.
## Steps
-### `params(name = :default, default_values_from: nil, base_class: Service::ContractBase, &block)`
+### `params(name = :default, default_values_from: nil, base_class: Service::ContractBase, from_resource: nil, only: nil, except: nil, &block)`
**Arguments**
- _name_: the name of the contract, in the case there is more than one. Defaults to `default`.
- _default_values_from_: name of a model to use to pre-fill the contract values. This is useful when you want some values of a model to be updated through a contract while applying other default values. A real-world example is available in the [`Chat::UpdateChannel`](https://github.com/discourse/discourse/blob/main/plugins/chat/app/services/chat/update_channel.rb#L39) service.
- _base_class_: the base class to use for the contract. This is particularly useful for reusing an existing contract (for example, you could have very similar contracts between a `Create` and a `Update` service). Defaults to `Service::ContractBase`.
+- _from_resource_: a resource whose writable attribute names and ActiveModel types are imported into the contract.
+- _only_: writable attribute names to import. Accepts strings or symbols. An empty array imports no attributes.
+- _except_: writable attribute names to exclude from the import. Accepts strings or symbols.
- _block_: the block containing all the validations, attribute definitions, etc.
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 `from_resource`, all writable attributes are imported by default. Use `only:` or `except:` to select the attributes for an action:
+
+```ruby
+params(from_resource: TopicResource, only: %i[title]) do
+ attribute :notify, :boolean, default: false
+ validates :title, presence: true
+end
+```
+
+Imports run before the block. Explicit attribute declarations override imported types through normal ActiveModel behavior. A declaration that omits the type preserves the imported type. Selection applies only to imports, so the block can declare additional parameters or declare an excluded attribute explicitly.
+
+Selection options require `from_resource:` and cannot be combined. Unknown or read-only selection names raise an error when the service is defined. Imports include only names and types.
+
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.
diff --git a/lib/service/base.rb b/lib/service/base.rb
index ca410e526f1..1414a91cf72 100644
--- a/lib/service/base.rb
+++ b/lib/service/base.rb
@@ -61,9 +61,13 @@
# # end
#
# # @!scope class
-# # @!method params(name = :default, default_values_from: nil, &block)
+# # @!method params(name = :default, default_values_from: nil, base_class: Service::ContractBase, from_resource: nil, only: nil, except: nil, &block)
# # @param name [Symbol] name for this contract
# # @param default_values_from [Symbol] name of the model to get default values from
+# # @param base_class [Class] base class for the contract
+# # @param from_resource [Class] resource whose writable names and types are imported
+# # @param only [Array<String, Symbol>] writable names to import
+# # @param except [Array<String, Symbol>] writable names to exclude from the import
# # @param block [Proc] a block containing validations
# # Checks the validity of the input parameters.
# # Implements ActiveModel::Validations and ActiveModel::Attributes.
diff --git a/lib/service/base/steps_helpers.rb b/lib/service/base/steps_helpers.rb
index f2f8407d7cc..4049da1b5f5 100644
--- a/lib/service/base/steps_helpers.rb
+++ b/lib/service/base/steps_helpers.rb
@@ -13,9 +13,14 @@ module Service
name = :default,
default_values_from: nil,
base_class: Service::ContractBase,
+ from_resource: nil,
+ only: nil,
+ except: nil,
&block
)
- contract_class = Class.new(base_class).tap { it.class_eval(&block) if block }
+ contract_class = Class.new(base_class)
+ ResourceImport.new(from_resource, only:, except:).apply_to(contract_class)
+ contract_class.class_eval(&block) if block
const_set("#{name.to_s.classify.sub("Default", "")}Contract", contract_class)
steps << ContractStep.new(name, class_name: contract_class, default_values_from:)
end
diff --git a/lib/service/resource_import.rb b/lib/service/resource_import.rb
new file mode 100644
index 00000000000..0374f7e4f4f
--- /dev/null
+++ b/lib/service/resource_import.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module Service
+ class ResourceImport
+ def initialize(resource, only: nil, except: nil)
+ raise ArgumentError, "only and except cannot be used together." if only && except
+ if !resource && (only || except)
+ raise ArgumentError, "#{only ? :only : :except} requires from_resource."
+ end
+
+ @attributes = resource ? resource.writable_attributes.index_by(&:name) : {}
+ @included_names = only&.map(&:to_s) || attributes.keys
+ @excluded_names = (except || []).map(&:to_s)
+ verify_names!
+ end
+
+ def apply_to(contract)
+ selected_attributes.each_value { contract.attribute(it.name, it.type) }
+ end
+
+ private
+
+ attr_reader :attributes, :included_names, :excluded_names
+
+ def selected_attributes = attributes.slice(*(included_names - excluded_names))
+
+ def unknown_names = (included_names + excluded_names) - attributes.keys
+
+ def verify_names!
+ return if unknown_names.empty?
+ raise ArgumentError, "#{unknown_names.join(", ")}: not writable resource attributes."
+ end
+ end
+end
diff --git a/spec/lib/service_spec.rb b/spec/lib/service_spec.rb
index 01ffa7beaf7..bc563c48a8f 100644
--- a/spec/lib/service_spec.rb
+++ b/spec/lib/service_spec.rb
@@ -155,6 +155,247 @@ RSpec.describe Service do
let(:args) { { params: {} } }
+ describe "Resource imports" do
+ let(:resource_class) do
+ Class.new(JsonApiKit::Resource) do
+ attribute :title, :string, writable: true
+ attribute :priority, :integer, writable: true
+ attribute :tags, :array, writable: true
+ attribute :created_at, :datetime
+ end
+ end
+ let(:options) { { from_resource: resource_class } }
+
+ context "when no block is supplied" do
+ subject(:declaration) { service_class.params(**options) }
+
+ let(:attribute_names) do
+ declaration
+ service_class::Contract.attribute_names
+ end
+ let(:title_type) { resource_class.writable_attributes.first.type }
+ let(:imported_title_type) do
+ declaration
+ service_class::Contract.attribute_types.fetch("title")
+ end
+
+ context "when only selects writable attributes" do
+ let(:options) { super().merge(only: %i[title tags]) }
+
+ it "imports the selected attributes" do
+ expect(attribute_names).to contain_exactly("title", "tags")
+ end
+ end
+
+ context "when except excludes writable attributes" do
+ let(:options) { super().merge(except: ["priority"]) }
+
+ it "imports the remaining attributes" do
+ expect(attribute_names).to contain_exactly("title", "tags")
+ end
+ end
+
+ context "when only selects no attributes" do
+ let(:options) { super().merge(only: []) }
+
+ it "imports no attributes" do
+ expect(attribute_names).to be_empty
+ end
+ end
+
+ context "when only and except are both supplied" do
+ let(:options) { super().merge(only: [:title], except: [:priority]) }
+
+ it "rejects the selection" do
+ expect { declaration }.to raise_error(ArgumentError, /only.*except.*together/i)
+ end
+ end
+
+ context "when only selects an unknown attribute" do
+ let(:options) { super().merge(only: [:missing]) }
+
+ it "identifies the invalid attribute" do
+ expect { declaration }.to raise_error(ArgumentError, /missing.*writable/i)
+ end
+ end
+
+ context "when only selects a read-only attribute" do
+ let(:options) { super().merge(only: [:created_at]) }
+
+ it "identifies the invalid attribute" do
+ expect { declaration }.to raise_error(ArgumentError, /created_at.*writable/i)
+ end
+ end
+
+ context "when except excludes an unknown attribute" do
+ let(:options) { super().merge(except: [:missing]) }
+
+ it "identifies the invalid attribute" do
+ expect { declaration }.to raise_error(ArgumentError, /missing.*writable/i)
+ end
+ end
+
+ context "when except excludes a read-only attribute" do
+ let(:options) { super().merge(except: [:created_at]) }
+
+ it "identifies the invalid attribute" do
+ expect { declaration }.to raise_error(ArgumentError, /created_at.*writable/i)
+ end
+ end
+
+ context "when only is supplied without a resource" do
+ let(:options) { super().except(:from_resource).merge(only: [:title]) }
+
+ it "requires a resource" do
+ expect { declaration }.to raise_error(ArgumentError, /only.*requires.*from_resource/i)
+ end
+ end
+
+ context "when except is supplied without a resource" do
+ let(:options) { super().except(:from_resource).merge(except: [:title]) }
+
+ it "requires a resource" do
+ expect { declaration }.to raise_error(ArgumentError, /except.*requires.*from_resource/i)
+ end
+ end
+
+ it "imports every writable attribute" do
+ expect(attribute_names).to contain_exactly("title", "priority", "tags")
+ end
+
+ it "uses the resource's resolved type" do
+ expect(imported_title_type).to equal(title_type)
+ end
+ end
+
+ context "when a block is supplied" do
+ let(:args) { super().merge(params:, **dependencies) }
+ let(:params) do
+ { title: "A title", priority: "2", tags: "ruby", notify: "1", created_at: "2026-10-14" }
+ end
+ let(:dependencies) { {} }
+ let(:contract_name) { :default }
+ let(:title_type) { nil }
+
+ before do
+ type = title_type
+ service_class.params(contract_name, **options) do
+ attribute :title, type, default: "Untitled"
+ attribute :notify, :boolean, default: false
+
+ validates :title, presence: true
+ end
+ end
+
+ context "when an imported attribute fails inline validation" do
+ let(:params) { super().merge(title: "") }
+
+ it "rejects invalid imported values" do
+ expect(result).to fail_a_contract
+ end
+ end
+
+ context "when an inline declaration supplies a type" do
+ let(:title_type) { :integer }
+ let(:params) { super().merge(title: "42") }
+
+ it "uses the inline type" do
+ expect(result.params.title).to eq(42)
+ end
+ end
+
+ context "when an inline declaration supplies only a default" do
+ let(:params) { super().except(:title) }
+
+ it "uses the inline default" do
+ expect(result.params.title).to eq("Untitled")
+ end
+ end
+
+ context "when an inline declaration omits the type" do
+ let(:params) { super().merge(title: 123) }
+
+ it "preserves the imported type" do
+ expect(result.params.title).to eq("123")
+ end
+ end
+
+ context "when only selects imported attributes" do
+ let(:options) { super().merge(only: [:priority]) }
+
+ it "preserves inline attributes outside the selection" do
+ expect(result.params.to_hash).to eq(title: "A title", priority: 2, notify: true)
+ end
+ end
+
+ context "when except excludes an inline attribute" do
+ let(:options) { super().merge(except: [:title]) }
+
+ it "preserves the inline declaration" do
+ expect(result.params.title).to eq("A title")
+ end
+ end
+
+ context "when a base contract is supplied" do
+ let(:options) { super().merge(base_class: base_contract) }
+ let(:base_contract) do
+ Class.new(Service::ContractBase) { attribute :author_id, :integer, default: 7 }
+ end
+
+ it "combines inherited and imported attributes" do
+ expect(result.params.to_hash).to eq(
+ author_id: 7,
+ title: "A title",
+ priority: 2,
+ tags: ["ruby"],
+ notify: true,
+ )
+ end
+ end
+
+ context "when a model supplies default values" do
+ let(:options) { super().merge(default_values_from: :post) }
+ let(:params) { super().except(:priority) }
+ let(:dependencies) { super().merge(post: { title: "Original", priority: "3" }) }
+
+ it "combines model defaults with supplied values" do
+ expect(result.params.to_hash).to eq(
+ title: "A title",
+ priority: 3,
+ tags: ["ruby"],
+ notify: true,
+ )
+ end
+ end
+
+ context "when the contract has a name" do
+ let(:contract_name) { :post }
+
+ it "exposes the imported values through the named contract" do
+ expect(result.post_contract.to_hash).to eq(
+ title: "A title",
+ priority: 2,
+ tags: ["ruby"],
+ notify: true,
+ )
+ end
+ end
+
+ it "runs with ordinary parameters" do
+ expect(result).to run_successfully
+ end
+
+ it "coerces writable attributes and inline parameters" do
+ expect(result.params.to_hash).to eq(
+ title: "A title",
+ priority: 2,
+ tags: ["ruby"],
+ notify: true,
+ )
+ end
+ end
+ end
+
describe "Reusability" do
before do
another_contract =