[LRUG] Can't hide instance method if defined in native extension?

James Adam james at lazyatom.com
Sun Nov 13 14:29:54 PST 2011


As I think you've demonstrated for yourself, you cannot "override" a method defined in a class by including a module with that method; your only option is to alias the existing method out of the way by doing something similar to alias_method_chain in Rails.


On 13 Nov 2011, at 22:25, "Peter Vrabel" <kybu at kybu.org> wrote:

> Hi guys,
> 
> I recently came across a strange behavior. I would like to measure time spent executing Mysql statement, so I tried to hide 'execute' instance method of Mysql::Stmt and my first idea was to use my custom module that I include into Mysql::Stmt class. But then I found that I can't do that, original 'execute' method is always called. Here is a small edited snippet:
> 
> require 'mysql'
> 
> module MyStmt
>  def new_method ; puts "new_method" end
>  def execute(*args) ; puts "mine!"  end
> end
> 
> class Mysql::Stmt
>  include MyStmt
> end
> 
> db = Mysql.new('host', 'user', 'passwd', 'db')
> stmt = db.prepare("select * from information_schema.tables")
> 
> p stmt.method(:execute)
> p stmt.method(:new_method)
> 
> It gives this output:
> 
> #<Method: Mysql::Stmt#execute>
> #<Method: Mysql::Stmt(MyStmt)#new_method>
> 
> If that is the case, it seems to me like a quite serious inconsistency of how 'include' works. As a BFU I don't really care if a particular gem is native or not, I would expect that 'include' works in the same way in any case. Anybody could shed some light on this? Do I miss something?
> 
> alias_method works as expected.
> 
> Thanks.
> 
> Cheers,
> kybu
> 
> 
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org



More information about the Chat mailing list