I have library code that overrides Ar\'s find method. I also include the module for all Association classes so both MyModel.find and @parent.my_models.find work and apply the co
You want to override find_every
, which is the AR method that will ultimately run find_by_sql
with the corresponding query. Overriding find
won't work for customized finders, and it's just more fragile.
But to be compatible with other plugins you can't just overload this method. Instead, alias it and call the original implementation after doing what you want:
module MyPlugin
def self.included(base)
class << base
alias_method :find_every_without_my_plugin, :find_every
def find_every(*args)
# do whatever you need ...
find_every_without_my_plugin(*args)
end
end
end
end
ActiveRecord::Base.send :include, MyPlugin
This will enable your plugin for all classes. How do you want to control which models are enabled? Maybe a standard plugin accessor?
class User < ActiveRecord::Base
my_plugin
end
To support this you need to move the class << base
to a class method (thus base
should be self
). Like:
module MyPlugin
def self.included(base)
class << base
base.extend ClassMethods
end
end
module ClassMethods
def my_plugin
class << self
alias_method :find_every_without_my_plugin, :find_every
# ...
end
end
end
end