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

Support methods added by ActiveRecord delegated types #1240

Open
fcheung opened this issue Oct 21, 2022 · 0 comments
Open

Support methods added by ActiveRecord delegated types #1240

fcheung opened this issue Oct 21, 2022 · 0 comments

Comments

@fcheung
Copy link
Contributor

fcheung commented Oct 21, 2022

One of the apps I work on uses delegated types ( https://api.rubyonrails.org/classes/ActiveRecord/DelegatedType.html ).

Given

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
end

then in addition to the underlying association methods, rails defines (this is just from the docs)

Entry#entryable_class # => +Message+ or +Comment+
Entry#entryable_name  # => "message" or "comment"
Entry.messages        # => Entry.where(entryable_type: "Message")
Entry#message?        # => true when entryable_type == "Message"
Entry#message         # => returns the message record, when entryable_type == "Message", otherwise nil
Entry#message_id      # => returns entryable_id, when entryable_type == "Message", otherwise nil
Entry.comments        # => Entry.where(entryable_type: "Comment")
Entry#comment?        # => true when entryable_type == "Comment"
Entry#comment         # => returns the comment record, when entryable_type == "Comment", otherwise nil
Entry#comment_id      # => returns entryable_id, when entryable_type == "Comment", otherwise nil

I'd like it if tapioca could include these methods in generated rbis & thought I would have a go at adding support for this, however unlike associations, rails doesn't retain any memory of how it defined those methods - it just defines them (see implementation https://github.com/rails/rails/blob/main/activerecord/lib/active_record/delegated_type.rb#L206) - there's no state you can iterate over like you can with associations.

Is there a suggested approach for handling cases like this? I saw that the compiled for frozen record overwrites a method from that library (https://github.com/Shopify/tapioca/blob/main/lib/tapioca/dsl/extensions/frozen_record.rb ) in order to stash some information for tapioca - would something like that be acceptable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant