Last active
November 13, 2019 21:13
-
-
Save macobo/6cb31a4cd355138d98c52bdf25c509dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ApplicationRecord < ActiveRecord::Base | |
| self.abstract_class = true | |
| # This method adds a hidden activerecord relationship. | |
| # | |
| # The relationship is hidden as you cannot access them via `model.assocation`, but can be | |
| # preloaded and can be accessed within specific components by wrapping the model. | |
| # | |
| # Use this for associations on models which have been moved under specific components and | |
| # expose these associations instead in the model itself. | |
| def self.hide_association(relation, association_name, *args) | |
| # rubocop:disable GitlabSecurity/PublicSend | |
| send(relation, association_name, *args) | |
| # rubocop:enable GitlabSecurity/PublicSend | |
| undef_method(association_name) | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AnotherComponent::Models::Bar < ApplicationRecord | |
| def self.for(foo_model) | |
| foo_model.association(:bars).reader | |
| end | |
| end | |
| # Example usage | |
| SomeComponent::Models::Foo | |
| .includes(:bars) | |
| .map { |foo| | |
| # This would typically happen somewhere inside AnotherComponent | |
| AnotherComponent::Models::Bar.for(foo) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class SomeComponent::Models::Foo < ApplicationRecord | |
| # Instead of `has_many, :bars, class_name: 'AnotherComponent::Models::Bar'` | |
| hide_association :has_many, :bars, class_name: 'AnotherComponent::Models::Bar' | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment