diff --git a/Gemfile.lock b/Gemfile.lock index 60926b7..a4e168a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - activemodel-entity (0.16.1) + activemodel-entity (0.17.0) actionpack (>= 7) activemodel (>= 7) activesupport (>= 7) diff --git a/README.md b/README.md index 811bd6b..9d75804 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,72 @@ If bundler is not being used to manage dependencies, install the gem by executin ## Usage -TODO: Write usage instructions here +### Discriminated unions + +A base entity can name a tag attribute and a closed mapping of tag to subclass, STI-style. +Mapping values may be class names of classes defined later, or constants: + +```ruby +class ThreadContext + include ActiveModel::Entity + + discriminated_by :type, admin: "ThreadContext::Admin", whatsapp: "ThreadContext::Whatsapp" +end + +class ThreadContext::Admin < ThreadContext; end + +class ThreadContext::Whatsapp < ThreadContext + attribute :phone_number_id, :string + attribute :wa_id, :string +end +``` + +`discriminated_by` declares the `type` string attribute on the base unless it already exists. Each +subclass gets its tag as the attribute's default, `represent` serializes it, and a subclass whose tag +does not match its mapping entry is invalid. + +Building through the base dispatches on the tag (string or symbol key; `from_json` reads the +camelized key like any other attribute); a missing or unknown tag raises an `ArgumentError`. Building +a subclass directly works as before: + +```ruby +ThreadContext.new(type: "whatsapp", wa_id: "1") # => # +ThreadContext.from_json("type" => "admin") # => # +ThreadContext::Whatsapp.new(wa_id: "1").type # => "whatsapp" +ThreadContext.new(type: "sms") # ArgumentError: unknown type tag "sms" +``` + +Attributes typed with the base (`attribute :context, :entity, class_name: "ThreadContext"`, +`attribute :contexts, :array, of: "ThreadContext"`) cast hashes to the matching subclass and keep +subclass instances as they are. + +The base's JSON schema is a `oneOf` of the subclasses with an OpenAPI 3 `discriminator`; each +subclass pins its tag as a required single-value enum: + +```ruby +ThreadContext.as_json_schema +# { +# oneOf: [{ "$ref": "#/components/schemas/ThreadContext.Admin" }, { "$ref": "#/components/schemas/ThreadContext.Whatsapp" }], +# discriminator: { +# propertyName: "type", +# mapping: { "admin" => "#/components/schemas/ThreadContext.Admin", "whatsapp" => "#/components/schemas/ThreadContext.Whatsapp" } +# } +# } + +ThreadContext::Whatsapp.as_json_schema +# { +# type: :object, +# required: ["type"], +# properties: { +# "type" => { type: :string, enum: ["whatsapp"] }, +# "phoneNumberId" => { type: :string }, +# "waId" => { type: :string } +# } +# } +``` + +With `inline: true` the `oneOf` carries the subclass schemas themselves and the `discriminator` keeps +only `propertyName`, since there are no refs for a `mapping` to point at. ## Development diff --git a/lib/active_model/entity.rb b/lib/active_model/entity.rb index a9abca8..96f98aa 100644 --- a/lib/active_model/entity.rb +++ b/lib/active_model/entity.rb @@ -17,6 +17,7 @@ require_relative "entity/validations/exclusive_presence_validator" require_relative "entity/validations/validates_nested" require_relative "entity/pattern_matcheable" +require_relative "entity/discriminator" # Load Railtie if Rails is defined require_relative "entity/railtie" if defined?(Rails::Railtie) @@ -39,6 +40,7 @@ module Entity include ActiveModel::Entity::Validations include ActiveModel::Entity::Validations::ValidatesNested include ActiveModel::Entity::PatternMatcheable + include ActiveModel::Entity::Discriminator end end end diff --git a/lib/active_model/entity/discriminator.rb b/lib/active_model/entity/discriminator.rb new file mode 100644 index 0000000..6d82962 --- /dev/null +++ b/lib/active_model/entity/discriminator.rb @@ -0,0 +1,156 @@ +# frozen_string_literal: true + +module ActiveModel + module Entity + # STI-style unions: a base entity names a tag attribute and a closed mapping of tag => subclass. + # + # class ThreadContext + # include ActiveModel::Entity + # + # discriminated_by :type, admin: "ThreadContext::Admin", whatsapp: "ThreadContext::Whatsapp" + # end + # + # Going through the base (+new+, +from_json+, +represent+) dispatches on the tag; a subclass + # carries its tag as the attribute's default and validates it. The base's JSON schema is a + # +oneOf+ of the subclasses with an OpenAPI +discriminator+. + module Discriminator + extend ActiveSupport::Concern + + included do + class_attribute :discriminator, instance_accessor: false + end + + # The tag attribute, the mapping and the base that declared them. Mapping values may be + # class names of classes defined later, so they are only constantized on first use. + class Definition + attr_reader :base, :attribute, :mapping + + def initialize(base, attribute, mapping) + @base = base + @attribute = attribute.to_s + @mapping = mapping.transform_keys(&:to_s).freeze + end + + def classes + @classes ||= mapping.transform_values { _1.is_a?(Class) ? _1 : _1.to_s.constantize } + end + + def tag_for(klass) + classes.key(klass) + end + + def resolve(tag) + raise ArgumentError, "#{base}: missing #{attribute} tag, expected one of #{tags_list}" if tag.nil? + + classes.fetch(tag.to_s) { raise ArgumentError, "#{base}: unknown #{attribute} tag #{tag.inspect}, expected one of #{tags_list}" } + end + + private + + def tags_list + mapping.keys.map(&:inspect).join(", ") + end + end + + # Class-level methods. + module ClassMethods + def discriminated_by(name, mapping) + attribute(name, :string) unless attribute_types.key?(name.to_s) + self.discriminator = Definition.new(self, name, mapping) + validate :validate_discriminator_tag + descendants.each { define_discriminator_default(_1) } + end + + # The tag this class is mapped under, nil for the base and for unmapped subclasses. + def discriminator_tag + return @discriminator_tag if defined?(@discriminator_tag) + + @discriminator_tag = discriminator&.tag_for(self) + end + + def discriminated_base? + discriminator&.base.equal?(self) + end + + def inherited(subclass) + super + + define_discriminator_default(subclass) if discriminator + end + + # Without attributes the base itself is built, which is what +from_json+ starts from. + def new(*args, **kwargs, &) + target = discriminator_target(args.first || kwargs.presence, discriminator&.attribute) + target.equal?(self) ? super : target.new(*args, **kwargs, &) + end + + def from_json(json) + target = discriminator_target(json, discriminator&.attribute&.camelize(:lower)) + target.equal?(self) ? super : target.from_json(json) + end + + def represent(object_or_hash, options = {}) + return super unless discriminated_base? + + target = object_or_hash.is_a?(self) ? object_or_hash.class : discriminator.resolve(fetch_field_value(object_or_hash, discriminator.attribute)) + target.equal?(self) ? super : target.represent(object_or_hash, options) + end + + def represent_all(sources, options = {}) + return super unless discriminated_base? + + sources.map { _1.nil? ? nil : represent(_1, options) } + end + + def as_json_schema(inline: false) + return union_json_schema(inline:) if discriminated_base? + + schema = super + tag = discriminator_tag + return schema unless tag + + name = discriminator.attribute.camelize(:lower) + schema[:properties][name][:enum] = [tag] + schema[:required] |= [name] + schema + end + + private + + def define_discriminator_default(subclass) + subclass.attribute(discriminator.attribute, default: -> { subclass.discriminator_tag }) + end + + # The class a source hash builds: self unless this is a discriminated base, in which + # case the tag under +key+ (string or symbol) picks the subclass. + def discriminator_target(source, key) + return self unless discriminated_base? && source + + tag = source[key] + tag = source[key.to_sym] if tag.nil? + discriminator.resolve(tag) + end + + def union_json_schema(inline:) + definition = discriminator + refs = definition.classes.transform_values(&:json_schema_ref) + one_of = inline ? definition.classes.values.map { _1.as_json_schema(inline:) } : refs.values.map { { "$ref": _1 } } + discriminator_schema = { propertyName: definition.attribute.camelize(:lower) } + discriminator_schema[:mapping] = refs unless inline + + { oneOf: one_of, discriminator: discriminator_schema, description: meta_descriptions[nil].first }.compact + end + end + + private + + def validate_discriminator_tag + definition = self.class.discriminator + value = public_send(definition.attribute) + return if (tag = self.class.discriminator_tag) && value == tag + + errors.add(definition.attribute.to_sym, :inclusion, value:) + end + end + end +end diff --git a/lib/active_model/entity/version.rb b/lib/active_model/entity/version.rb index 479e03a..3725774 100644 --- a/lib/active_model/entity/version.rb +++ b/lib/active_model/entity/version.rb @@ -2,6 +2,6 @@ module ActiveModel module Entity - VERSION = "0.16.1" + VERSION = "0.17.0" end end diff --git a/spec/active_model/entity/discriminator_spec.rb b/spec/active_model/entity/discriminator_spec.rb new file mode 100644 index 0000000..f409906 --- /dev/null +++ b/spec/active_model/entity/discriminator_spec.rb @@ -0,0 +1,236 @@ +# frozen_string_literal: true + +module DiscriminatorTest + class ThreadContext + include ActiveModel::Entity + + desc "Where a thread came from" + desc "Which kind of context this is" + attribute :type, :string + + discriminated_by :type, admin: "DiscriminatorTest::Admin", whatsapp: "DiscriminatorTest::Whatsapp" + end + + class Admin < ThreadContext; end + + class Whatsapp < ThreadContext + attribute :phone_number_id, :string + attribute :wa_id, :string + + validates :wa_id, presence: true + end + + class Thread + include ActiveModel::Entity + + attribute :context, :entity, class_name: "DiscriminatorTest::ThreadContext" + attribute :contexts, :array, of: "DiscriminatorTest::ThreadContext" + + validates_nested + end + + # Constants in the mapping, subclasses declared before the mapping, a multi-word tag attribute. + class Shape + include ActiveModel::Entity + + class Circle < self; end + class Square < self; end + + discriminated_by :shape_kind, circle: Circle, square: Square + end +end + +RSpec.describe ActiveModel::Entity::Discriminator do + let(:admin_ref) { "#/components/schemas/DiscriminatorTest.Admin" } + let(:whatsapp_ref) { "#/components/schemas/DiscriminatorTest.Whatsapp" } + + describe "the tag attribute" do + it "is set on new and serialized by represent" do + expect(DiscriminatorTest::Admin.new.type).to eq("admin") + expect(DiscriminatorTest::Whatsapp.new(wa_id: "1").type).to eq("whatsapp") + expect(DiscriminatorTest::Admin.represent(DiscriminatorTest::Admin.new)).to eq({ "type" => "admin" }) + expect(DiscriminatorTest::Whatsapp.represent(DiscriminatorTest::Whatsapp.new(wa_id: "1"))) + .to eq({ "type" => "whatsapp", "phoneNumberId" => nil, "waId" => "1" }) + end + + it "is set on subclasses declared before the mapping" do + expect(DiscriminatorTest::Shape::Circle.new.shape_kind).to eq("circle") + expect(DiscriminatorTest::Shape::Square.new.shape_kind).to eq("square") + end + end + + describe "dispatch on the base" do + it "builds the subclass from json with string keys" do + context = DiscriminatorTest::ThreadContext.from_json({ "type" => "whatsapp", "waId" => "1" }) + + expect(context).to be_instance_of(DiscriminatorTest::Whatsapp) + expect(context.wa_id).to eq("1") + end + + it "builds the subclass from json with symbol keys" do + expect(DiscriminatorTest::ThreadContext.from_json({ type: :admin })).to be_instance_of(DiscriminatorTest::Admin) + end + + it "builds the subclass from ActionController::Parameters" do + context = DiscriminatorTest::ThreadContext.from_json(ActionController::Parameters.new(type: "whatsapp", waId: "1")) + + expect(context).to be_instance_of(DiscriminatorTest::Whatsapp) + expect(context.wa_id).to eq("1") + end + + it "builds the subclass with new" do + expect(DiscriminatorTest::ThreadContext.new(type: "whatsapp", wa_id: "1")).to be_instance_of(DiscriminatorTest::Whatsapp) + expect(DiscriminatorTest::ThreadContext.new({ "type" => "admin" })).to be_instance_of(DiscriminatorTest::Admin) + end + + it "honours the camelized tag key in from_json and the plain one in new" do + expect(DiscriminatorTest::Shape.from_json({ "shapeKind" => "circle" })).to be_instance_of(DiscriminatorTest::Shape::Circle) + expect(DiscriminatorTest::Shape.new(shape_kind: "square")).to be_instance_of(DiscriminatorTest::Shape::Square) + end + + it "builds a subclass directly regardless of the tag" do + expect(DiscriminatorTest::Whatsapp.new(wa_id: "1")).to be_instance_of(DiscriminatorTest::Whatsapp) + expect(DiscriminatorTest::Admin.from_json({ "type" => "admin" })).to be_instance_of(DiscriminatorTest::Admin) + expect(DiscriminatorTest::Admin.new(type: "whatsapp")).to be_instance_of(DiscriminatorTest::Admin) + end + + it "raises on an unknown tag" do + expect { DiscriminatorTest::ThreadContext.new(type: "sms") } + .to raise_error(ArgumentError, 'DiscriminatorTest::ThreadContext: unknown type tag "sms", expected one of "admin", "whatsapp"') + end + + it "raises on a missing tag" do + expect { DiscriminatorTest::ThreadContext.from_json({ "waId" => "1" }) } + .to raise_error(ArgumentError, 'DiscriminatorTest::ThreadContext: missing type tag, expected one of "admin", "whatsapp"') + end + + it "represents through the base using the subclass" do + whatsapp = DiscriminatorTest::Whatsapp.new(wa_id: "1") + + expect(DiscriminatorTest::ThreadContext.represent(whatsapp)).to eq({ "type" => "whatsapp", "phoneNumberId" => nil, "waId" => "1" }) + expect(DiscriminatorTest::ThreadContext.represent({ type: "admin" })).to eq({ "type" => "admin" }) + end + end + + describe "as a nested attribute" do + it "casts a hash to the right subclass" do + thread = DiscriminatorTest::Thread.new(context: { type: "whatsapp", wa_id: "1" }) + + expect(thread.context).to be_instance_of(DiscriminatorTest::Whatsapp) + expect(thread.context.wa_id).to eq("1") + end + + it "parses json to the right subclass" do + thread = DiscriminatorTest::Thread.from_json({ "context" => { "type" => "admin" } }) + + expect(thread.context).to be_instance_of(DiscriminatorTest::Admin) + end + + it "keeps a subclass instance" do + admin = DiscriminatorTest::Admin.new + + expect(DiscriminatorTest::Thread.new(context: admin).context).to equal(admin) + expect(DiscriminatorTest::Thread.new(contexts: [admin]).contexts.first).to equal(admin) + end + + it "casts an array of hashes to the right subclasses" do + thread = DiscriminatorTest::Thread.from_json({ "contexts" => [{ "type" => "admin" }, { "type" => "whatsapp", "waId" => "1" }] }) + + expect(thread.contexts.map(&:class)).to eq([DiscriminatorTest::Admin, DiscriminatorTest::Whatsapp]) + expect(thread.contexts.last.wa_id).to eq("1") + end + + it "represents with the subclass attributes" do + thread = DiscriminatorTest::Thread.new(context: { type: "whatsapp", wa_id: "1" }, contexts: [{ type: "admin" }, nil]) + + expect(DiscriminatorTest::Thread.represent(thread)).to eq({ + "context" => { "type" => "whatsapp", "phoneNumberId" => nil, "waId" => "1" }, + "contexts" => [{ "type" => "admin" }, nil] + }) + end + end + + describe "validation" do + it "rejects a tag that is not the subclass's own" do + context = DiscriminatorTest::Admin.new(type: "whatsapp") + + expect(context).not_to be_valid + expect(context.errors[:type]).to eq(["is not included in the list"]) + expect(DiscriminatorTest::Admin.new(type: nil)).not_to be_valid + end + + it "validates the nested subclass's own attributes" do + expect(DiscriminatorTest::Thread.new(context: { type: "whatsapp", wa_id: "1" })).to be_valid + + thread = DiscriminatorTest::Thread.new(context: { type: "whatsapp" }, contexts: [{ type: "admin" }]) + + expect(thread).not_to be_valid + expect(thread.errors[:context]).to eq(['Error in nested entity #0 for wa_id: ["can\'t be blank"]']) + expect(thread.errors[:contexts]).to be_empty + end + end + + describe "equality" do + it "holds between two same-tag instances" do + expect(DiscriminatorTest::Admin.new).to eq(DiscriminatorTest::Admin.new) + expect(DiscriminatorTest::ThreadContext.new(type: "admin")).to eq(DiscriminatorTest::Admin.new) + expect(DiscriminatorTest::Whatsapp.new(wa_id: "1")).not_to eq(DiscriminatorTest::Whatsapp.new(wa_id: "2")) + expect(DiscriminatorTest::Admin.new.inspect).to eq("# "admin" }.inspect}>") + end + end + + describe "json schema" do + it "emits oneOf of refs with a discriminator mapping for the base" do + expect(DiscriminatorTest::ThreadContext.as_json_schema).to eq({ + oneOf: [{ "$ref": admin_ref }, { "$ref": whatsapp_ref }], + discriminator: { propertyName: "type", mapping: { "admin" => admin_ref, "whatsapp" => whatsapp_ref } }, + description: "Where a thread came from" + }) + end + + it "emits oneOf of inline schemas for the base" do + expect(DiscriminatorTest::ThreadContext.as_json_schema(inline: true)).to eq({ + oneOf: [DiscriminatorTest::Admin.as_json_schema(inline: true), DiscriminatorTest::Whatsapp.as_json_schema(inline: true)], + discriminator: { propertyName: "type" }, + description: "Where a thread came from" + }) + end + + it "fixes the tag as a required enum on a subclass" do + expect(DiscriminatorTest::Admin.as_json_schema).to eq({ + type: :object, + required: ["type"], + properties: { "type" => { type: :string, enum: ["admin"], description: "Which kind of context this is" } } + }) + + expect(DiscriminatorTest::Whatsapp.as_json_schema).to eq({ + type: :object, + required: %w[waId type], + properties: { + "type" => { type: :string, enum: ["whatsapp"], description: "Which kind of context this is" }, + "phoneNumberId" => { type: :string }, + "waId" => { type: :string } + } + }) + end + + it "camelizes the discriminator property name" do + expect(DiscriminatorTest::Shape.as_json_schema[:discriminator][:propertyName]).to eq("shapeKind") + expect(DiscriminatorTest::Shape::Circle.as_json_schema[:properties]["shapeKind"]).to eq({ type: :string, enum: ["circle"] }) + end + + it "refers to the base from an attribute typed with it" do + schema = DiscriminatorTest::Thread.as_json_schema + + expect(schema[:properties]["context"]).to eq({ "$ref": "#/components/schemas/DiscriminatorTest.ThreadContext" }) + expect(schema[:properties]["contexts"]).to eq({ items: { "$ref": "#/components/schemas/DiscriminatorTest.ThreadContext" }, type: :array }) + end + + it "inlines the union into an attribute typed with it" do + schema = DiscriminatorTest::Thread.as_json_schema(inline: true) + + expect(schema[:properties]["context"]).to eq(DiscriminatorTest::ThreadContext.as_json_schema(inline: true)) + expect(schema[:properties]["contexts"][:items]).to eq(DiscriminatorTest::ThreadContext.as_json_schema(inline: true)) + end + end +end