Forum: Ruby alias_method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
å??å­?æ±? (Guest)
on 2006-05-18 11:20
(Received via mailing list)
hi, i want to extend the ActiveRecord::Base.establish_connection, i do
it as fellow:

module ActiveRecordExtension
def self.included(klass) #nodoc
klass.extend(ClassMethods)
klass.class_eval do
alias_method :old_establish_connection, :establish_connection
alias_method :establish_connection, :my_establish_connection
end
end

module ClassMethods
def my_establish_connection(spec = nil)
old_establish_connection(spec)
end
end
end

when it be included, then a error issue:

./lib/activerecord/extension.rb:18:in `alias_method': undefined method
`establis
h_connection' for class `ActiveRecord::Base' (NameError), but the
ActiveRecord:Base.respond_to(:establis
h_connection) is true.

why?
ts (Guest)
on 2006-05-18 13:12
(Received via mailing list)
>>>>> "B" == =?GB2312?B?wfXDz72t?=  <GB2312> writes:

B> ./lib/activerecord/extension.rb:18:in `alias_method': undefined
method
B> `establis
B> h_connection' for class `ActiveRecord::Base' (NameError), but the
B> ActiveRecord:Base.respond_to(:establis
B> h_connection) is true.

 You want probably alias with instance_eval

moulon% cat b.rb
#!/usr/bin/ruby
module A
   class B
      def self.b
      end
   end
end

def included(klass)
   klass.instance_eval do
      alias c b
   end
   p "instance_eval : #{klass.respond_to?(:c)}"

   begin
      klass.class_eval do
         alias d b
      end
   rescue
      p "class_eval : #{$!}"
   end
end

p "A::B : #{A::B.respond_to?(:b)}"
included(A::B)
moulon%

moulon% ./b.rb
"A::B : true"
"instance_eval : true"
"class_eval : undefined method `b' for class `A::B'"
moulon%




Guy Decoux
This topic is locked and can not be replied to.