2011-05-09 168 views
1

我有以下Ruby脚本,其中Foo类包含模块Baz,模块Baz有一个包含的钩子以使包含类(Foo)的Bar扩展。我只是想知道为什么:如何在类上下文中扩展Ruby模块?

class << klass 
    extend Bar #this doesn't work. Why? 
end 

不工作而:

klass.extend(Bar) works. 

这里是我的代码:

#! /usr/bin/env ruby 

module Baz 
    def inst_method 
    puts "dude" 
    end 

    module Bar 
    def cls_method 
     puts "Yo" 
    end 
    end 

    class << self 
    def included klass 
     # klass.extend(Bar) this works, but why the other approach below doesn't? 
     class << klass 
     extend Bar #this doesn't work. Why? 
     def hello 
      puts "hello" 
     end 
     end 
    end 
    end 
end 

class Foo 
    include Baz 
end 

foo = Foo.new 
foo.inst_method 
Foo.hello 
Foo.cls_method 

回答

1

class << klass身体,self指单例类的klass,而不是klass本身,而在klass.extend(Bar),接收机本身是klass。差异来自那里。

class A 
end 

class << A 
    p self # => #<Class:A> # This is the singleton class of A, not A itself. 
end 

p A # => A  # This is A itself. 

而且因为你想申请extendklassclass << klass体内做是行不通的。

1

你想要的是在类对象(klass)上调用extend而不是单例类(类< < klass)。

因此,因为要调用单例类extend方法下面的代码不起作用:

class << klass 
    extend Bar # doesn't work because self refers to the the singleton class of klass 
    def hello 
     puts "hello" 
    end 
    end 
+0

谢谢你的解释,我才意识到,在单例类,我需要使用包括而不是扩展吧。 – 2011-05-09 03:11:07