Given the following ActiveRecord model:
class User < ActiveRecord::Base
has_many :games
def name
"Joe"
end
def city
"Chicago"
end
end
I’d like to retrieve a list of the methods I added directly to the User class (and not those added by extending ActiveRecord and/or adding associations). Example output:
["name","city"]
Calling User.instance_methods(false) returns method added by ActiveRecord:
["validate_associated_records_for_games", "games", "game_ids", "games=", "game_ids=", "after_create_or_update_associated_records_for_games", "before_save_associated_records_for_games"]
Along with any model attributes from database columns. I’d like to exclude those and just get the custom methods on the subclass.
My purpose is method tracing: I’d like to trace my custom methods while excluding those added by ActiveRecord.
Any ideas?
Use a
method_addedhook which adds method names to a list, and monkey patch Active Record so that methods added by AR are not added to that list.If you don’t want to crack AR open and start poking around, you could also define a “class macro” which defines a method and adds it to the list. For your own custom methods, use the class macro rather than
def.If you’re not familiar with what I’m referring to as a “class macro”, it’s simply a method like this:
Using something like
mydefto define methods rather thandefis definitely ugly, but it would solve the problem without requiring any monkey-patching.