2013-11-04 152 views
0

包括方法假設我有這個使用紅寶石

module Command 
    extend ActiveSupport::Concern 

     included do 
     @path ||= File.join("#{file_path}", "some_file") 
     end 

     def file_path 
     File.expand_path("some_other_file") 
     end 
... 

當包含模塊,我得到undefined local variable or method file_path。那麼有沒有辦法,使file_path方法在包含模塊時被識別? (當然沒有把file_pathincluded法)

+0

['Module#included'](http://ruby-doc.org/core-2.0.0/Module.html#method-i-included)沒有佔用block ..在哪裏找到代碼? –

回答

1

您所呼叫的方法file_path,在方法includeddo..end塊。這意味着與範圍設置爲Command類。但file_path是instance_method,所以Command.file_path正在拋出一個合法的錯誤。您必須調用方法file_path,該類包含Command模塊。一個例子來說明這個 -

module A 
    def self.included(mod) 
     p foo 
    end 
    def foo 
     2 
    end 
end 

class B 
    include A 
end 

# `included': undefined local variable or method `foo' for A:Module (NameError) 

該錯誤是因爲未來的方法included自我是A內部。 A沒有名爲foo的類方法,所以出現錯誤。現在來解決它,我們應該如下稱之爲:

module A 
    def self.included(mod) 
     p mod.new.foo 
    end 
    def foo 
     2 
    end 
end 

class B 
    include A 
end 

# >> 2 
+0

好的,謝謝有趣!但我應該更喜歡@newben的迴應。因爲'Command'模塊包含在某些類Generator user1611830

+0

@ user1611830哪一個適合你。因爲我不知道你正在使用的內部代碼。我只是給你提示,如何前進。 –

1

你可以試試這個:

模塊命令 延長的ActiveSupport ::關注

def self.extended(klass) 
    @path ||= File.join("#{klass.file_path}", "some_file") 
    end 

    def file_path 
    File.expand_path("some_other_file") 
    end 

,然後擴展你的模塊,你打電話它!