2011-05-09 169 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