Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to write Polymorphic Associated Objects via modules #30

Merged
merged 1 commit into from
Dec 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,68 @@ class Post::PublisherTest < ActiveSupport::TestCase
end
```

### Polymorphic Associated Objects

If you want to share logic between associated objects, you can do so via standard Ruby modules:

```ruby
# app/models/pricing.rb
module Pricing
# If you need to share an `extension` across associated objects you can override `Module::included` like this:
def self.included(object) = object.extension do
# Add common integration methods onto `Account`/`User` when the module is included.
# See the `extension` block in the `Extending` section above for an example.
end

def price_set?
# Instead of referring to `account` or `user`, use the `record` method to target either.
record.price_cents.positive?
end
end

# app/models/account/pricing.rb
class Account::Pricing < ActiveRecord::AssociatedObject
include ::Pricing
end

# app/models/user/pricing.rb
class User::Pricing < ActiveRecord::AssociatedObject
include ::Pricing
end
```

Now we can call `account.pricing.price_set?` & `user.pricing.price_set?`.

> [!NOTE]
> Polymorphic Associated Objects are definitely a more advanced topic,
> so you need to know your Ruby module hierarchy and how to track what `self` changes to fairly well.

#### Using `ActiveSupport::Concern` as an alternative

If you prefer the look of Active Support concerns, here's the equivalent to the above Ruby module:

```ruby
# app/models/pricing.rb
module Pricing
extend ActiveSupport::Concern

included do
extension do
# Add common integration methods onto `Account`/`User` when the concern is included.
end
end

def price_set?
# Instead of referring to `account` or `user`, use the `record` method to target either.
record.price_cents.positive?
end
end
```

Active Support concerns have some extra features that standard Ruby modules don't, like support for deeply-nested concerns and `class_methods do`.

In this case, if you're reaching for those, you're probably building something too intricate and potentially brittle.

### Active Job integration via GlobalID

Associated Objects include `GlobalID::Identification` and have automatic Active Job serialization support that looks like this:
Expand Down
Loading