2012-12-03 20 views
0

我正在編寫一個Rails 3.2生成器,並希望使用Thor::Shell::Basic實例方法(例如,askyes?),就像他們在official Rails guides on Application Templates中所做的一樣。如何在Rails Generator中使用Thor :: Shell :: Basic?

module MyNamespace 
    class ScaffoldGenerator < Rails::Generators::Base 
    source_root File.expand_path('../templates', __FILE__) 

    if yes? "Install MyGem?" 
     gem 'my_gem' 
    end 

    run 'bundle install' 
    end 
end 

這會給我一個NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class

我找不出一個乾淨的方法來使這些實例方法可用 - 我已經從Rails::Generators::Base繼承。

編輯:

啊,它可能沒有任何與雷神......我得到一個警告:

[WARNING] Could not load generator "generators/my_namespace/scaffold/scaffold_generator"

東西是不正確設置,雖然我用發電機產生髮電機...

回答

1

哦,是的,它確實需要與雷神做一些事情。

不要讓自己被警告弄糊塗。你知道Rails :: Generators使用Thor,所以走到the Thor Wiki並查看how Thor tasks work

導軌生成器執行將調用生成器中的任何方法。因此,請確保您將自己的東西整理到方法中:

module MyNamespace 
    class ScaffoldGenerator < Rails::Generators::Base 
    source_root File.expand_path('../templates', __FILE__) 

    def install_my_gem 
     if yes? "Install MyGem?" 
     gem 'my_gem' 
     end 
    end 

    def bundle 
     run 'bundle install' 
    end 
    end 
end 

確保將您的生成器放入正確的文件夾結構中,例如, lib/generators/my_namespace/scaffold_generator.rb

感謝您提出您的問題,老兄!

相關問題