Rails has_many overridden by an included module
I have a model that looks like this, the #friends met开发者_StackOverflow中文版hod overrides the association-generated method #friends:
class User < ActiveRecord::Base
has_many :friends
def friends
puts 'hi'
end
end
But when I refactor my code to look like this, the association-generated method #friends, doesn't get overridden by the included friends module:
module User
module Friends
def friends
puts 'hi'
end
end
end
require 'user/friends'
class User < ActiveRecord::Base
has_many :friends
include User::Friends
end
Why doesn't the associated-generated #friends get overridden by the included User::Friends#friends method?
Ruby's method lookup starts in the current class, if it doesn't find a match, it then looks in included modules and superclasses (IIRC, it looks in metaclasses, then modules, then superclasses, then superclasses metaclasses, etc). So when you define the method in the class, you are overriding, but when you define the method in the module, it doesn't get looked up.
In order to override the method, you should undef :friends
, or alias :old_friends :friends
(so that the original method is still available) inside of your module. It would probably work best to do it inside of the module's self.included
method
精彩评论