[Rails] Explanation of "alias_method"

d|vision|factory dim at dvisionfactory.com
Wed Feb 1 13:08:17 GMT 2006


Hi!

I'm trying to extend ActiveRecord's find method (Rails 1.0, Ruby 1.8.2), 
but I recognize a strange behaviour of the "alias_method" call.
I wrote a very simple script to explain my problem:

------------------------------------------------------
module ActiveRecordExtension
    def self.included(base)
        base.extend(ClassMethods)
        base.class_eval do
            class << self
                p "Aliasing find" # Used to check if alias_method isn't 
called twice
                alias_method :find_without_someting, :find
                alias_method :find, :find_with_someting
            end
        end
    end

    module ClassMethods # :nodoc:
        def find_with_something(*args)
          p "0"
          x = find_without_something(*args)
          p "1"
          return x
        end
    end   
end
------------------------------------------------------


After including this script I called:


------------------------------------------------------
p " --> find"
user = User.find(1)

p " --> find_with_something"
user = User.find_with_something(1)

p " --> find_without_something"
user = User.find_without_something(1)
------------------------------------------------------


and the result output was:


------------------------------------------------------
" --> find"
"0"
"0"
"0"
"1"
"1"
"1"
" --> find_with_something"
"0"
"0"
"0"
"1"
"1"
"1"
" --> find_without_something"
"0"
"0"
"1"
"1"
------------------------------------------------------

Can anyboby explain me what actully happens there. In my opinion, 
'find_without_something' should represent the original 'find' method, so 
there should not be any output. For a strange reason it outputs 0,0,1,1 
which in fact means that it calls 'find_with_something' twice.

Many thanks in advance for any hint or explanation.
Dim





More information about the Rails mailing list