2012-03-26 24 views
1

我正在生成一個新的Rails應用程序自定義生成的,我不喜歡這樣如何更改自定義導軌生成器的源代碼? (索爾)

require 'thor' 
require 'rails/generators/rails/app/app_generator' 

class AppBuilder < Rails::AppBuilder 
    include Thor::Actions 
    include Thor::Shell 
    ... 
end 

的問題是,如何添加一個新的源目錄(隨後被Thor::Actions#copy_file,Thor::Actions#template,和其他)?我的托爾的文檔中看到,Thor::Actions#source_paths持有源(它的路徑的數組),所以我試圖重寫它在我的班級裏(因爲我已經包括Thor::Actions):

def source_paths 
    [File.join(File.expand_path(File.dirname(__FILE__)), "templates")] + super 
end 

有了這個,我想補充的./templates目錄中,同時仍然保留Rails的一個(這就是爲什麼+ super在最後)。但它不起作用,它仍然列出Rails的唯一源代碼路徑。

我試過瀏覽Rails的源代碼,但是我找不到Rails如何將他的目錄放在源路徑中。我真的想知道:)

回答

4

這工作:

require 'thor' 
require 'rails/generators/rails/app/app_generator' 

module Thor::Actions 
    def source_paths 
    [MY_TEMPLATES] 
    end 
end 

class AppBuilder < Rails::AppBuilder 
    ... 
end 

我不明白爲什麼,但我已經花了太多時間在這個了,所以我不在乎。

3

雷神將訪問您的source_paths方法並將其添加到默認值:

# Returns the source paths in the following order: 
    # 
    # 1) This class source paths 
    # 2) Source root 
    # 3) Parents source paths 
    # 
    def source_paths_for_search 
    paths = [] 
    paths += self.source_paths 
    paths << self.source_root if self.source_root 
    paths += from_superclass(:source_paths, []) 
    paths 
    end 

因此,所有你需要在你的課上做的是:

class NewgemGenerator < Thor::Group 

    include Thor::Actions 

    def source_paths 
    ['/whatever', './templates'] 
    end 

end 

希望這有助於:)

+0

我試過了,我仍然得到這個錯誤:'找不到「」在任何源路徑。你目前的源代碼路徑是:path/to/gems/railties-3.2.2/lib/rails/generators/rails/app/templates,所以它根本沒有選擇它。 – 2012-03-30 12:12:51

+0

我添加了類定義,並且包含我用於回答的內容。 – 2012-03-30 17:50:31

+0

但是我必須繼承'Rails :: AppBuilder',因爲我重寫了那個類生成的東西。 – 2012-03-31 12:23:03

1

使用AppBuilder時,source_paths方法不起作用。 (這是使用rails模板的另一個選項)。我在這個類所在的app_builder.rb文件旁邊有一個文件目錄。我有這個工作,儘管看起來應該還有一個更優雅的方法。

tree . 
|-- app_builder.rb 
|-- files 
    `-- Gemfile 
class AppBuilder < Rails::AppBuilder 

    def initialize generator 
    super generator 
    path = File.expand_path(File.join('..', File.dirname(__FILE__))) 
    source_paths << path 
    end 

    def gemfile 
    copy_file 'files/Gemfile', 'Gemfile' 
    end 

,然後在控制檯上:

rails new my_app -b path_to_app_builder.rb

的點由於紅寶石文件 'app_builder.rb' 需要被咕嚕咕嚕向上和rails new命令更改後eval'd進入新的應用程序目錄(我認爲)。

相關問題