Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created November 3, 2022 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/c076216d740e310fd05213b042c4b693 to your computer and use it in GitHub Desktop.
Save baweaver/c076216d740e310fd05213b042c4b693 to your computer and use it in GitHub Desktop.
module AccessedAttributes
def self.included(klass)
association_proxy = Module.new do
def accessed_associations
@_accessed_associations ||= []
end
end
klass.reflect_on_all_associations.each do |association|
name = association.name
association_proxy.define_method(name) do |*args, &block|
accessed_associations << name
super(*args, &block)
end
end
klass.prepend(association_proxy)
end
end
class MyModel < ApplicationRecord
include AccessedAttributes
end
@baweaver
Copy link
Author

baweaver commented Nov 3, 2022

module AccessedAttributes
  def self.included(klass)
    association_proxy = Module.new do
      def accessed_associations
        @_accessed_associations ||= Set.new
      end

      def association(name)
        accessed_associations << name
        super(name)
      end
    end

    klass.prepend(association_proxy)
  end
end

Josh wins: https://twitter.com/josh_cheek/status/1588046756171890690

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment