CHAPTER 5 ?– BONUS FEATURES 110
First things first, you need to know how to override find. The simplest method is to open
up the ActiveRecord::Base class like we did at the beginning of the chapter and write a new
one. Of course, find does a lot of things already, and it??™s not the best idea to go overwriting
existing code. Whenever possible, you should make sure the old functions are still callable. We
can use alias_method to make sure that the original find call is available after we??™re through
poking around:
class ActiveRecord::Base
class << self
def find_with_rquery(*args, &blk)
# We'll get to this in a minute. But for now, don't break anything.
find_without_rquery(*args, &blk)
end
alias_method :find_without_rquery, :find
alias_method :find, :find_with_rquery
end
end
?– Note In Active Support, there exists a method that will basically do what we just did, but in a more
straightforward manner. It??™s called alias_method_chain. You give it the name of the method you want to
override and the name of the feature you??™re adding, and it will handle all of the aliasing itself.
Pages:
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269