[LRUG] Can't hide instance method if defined in native extension?
Peter Vrabel
kybu at kybu.org
Sun Nov 13 14:35:07 PST 2011
Well, I can do that if that class is written in pure Ruby, for example
'Set'. Consider this:
module MySet
def size
puts "mine!"
end
end
class Set
include MySet
end
set = Set.new [1, 2, 3]
p set.method(:size)
It gives following output:
#<Method: Set(MySet)#size>
Cheers,
kybu
On Sun, 13 Nov 2011 22:29:54 -0000, James Adam <james at lazyatom.com> wrote:
> 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
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
More information about the Chat
mailing list