2013-02-17 47 views
3

我正在通过CodeSchool的RubyBits工作,我参加了一个练习,我只是不理解:“确保AtariLibrary类仅包含LibraryUtils模块并让ActiveSupport :: Concern请注意加载它的依赖关系,然后重构LibraryUtils上的self.included方法以使用包含的方法。“使用扩展ActiveSupport :: Concern

module LibraryLoader 

    extend ActiveSupport::Concern 

    module ClassMethods 
    def load_game_list 
    end 
    end 
end 

module LibraryUtils 
    def self.included(base) 
    base.load_game_list 
    end 
end 

class AtariLibrary 
    include LibraryLoader 
    include LibraryUtils 
end 

基于该解决方案(如下图),好像ActiveSupport::Concern并不需要加载依赖护理 - 您需要包括LibraryUtils内LibraryLoader。

您能帮我理解ActiveSupport::Concern正在做什么,以及为什么需要在两个模块中通过extend调用?

module LibraryLoader 
    extend ActiveSupport::Concern 

    module ClassMethods 
    def load_game_list 
    end 
    end 
end 

module LibraryUtils 
    extend ActiveSupport::Concern 
    include LibraryLoader 

    #result of refactoring the self.included method 
    included do 
    load_game_list 
    end 
end 

class AtariLibrary 
    include LibraryUtils 
end 

谢谢!

回答

2

当你调用extend ActiveSupport :: Concern时,它会查找一个ClassMethods内部模块,并用它扩展你的'主机'类。然后,它会为您提供一个“包括”方法,它可以传递一个块:

包括做 some_function 端

该方法包括将所述包含类的上下文中运行。如果您的模块需要其他模块中的功能,则ActiveSupport :: Concern将负责为您提供依赖关系。