Skip to content

Instantly share code, notes, and snippets.

@macobo
Last active November 13, 2019 21:13
Show Gist options
  • Select an option

  • Save macobo/6cb31a4cd355138d98c52bdf25c509dd to your computer and use it in GitHub Desktop.

Select an option

Save macobo/6cb31a4cd355138d98c52bdf25c509dd to your computer and use it in GitHub Desktop.
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
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)
}
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