maeshimaの日記

メモ書きです

thor

ASCIIcasts - “Episode 242 - Thor”を見て。メモ。

Rakeの短所

  • 引数渡す方法が、環境変数しかない><
  • Rakeタスクは簡単にはグローバルに出来ない。基本的にローカルのプロジェクトでしか使えない。
  • Sakeとかいうツールを使えばその辺何とかなるけど、追加のツールが必要。

Thor

Thorは上記の問題を解決したRakeの代換ツール。Rails3のgeneratorはThorに依存してるので、Rails3いれると自動でインストールされる。Thor覚えるとgenerator作るのにも役立つ。

thor help

でヘルプ見れる。

Thorスクリプトの作り方

  • Thorスクリプトは、Rakeタスクと同じように、lib/tasks ディレクトリに入れる。
  • Thorクラスを継承したクラスを作る
  • クラスの名前はThorタスクの名前空間になる。
  • description付きのメソッド名がコマンドになる。
  • descメソッドでdescriptionを付けられる。第一引数でコマンド名、第二引数でdescriptionを定義できる。
  • thor listで使えるthorコマンドのリストを表示
  • method_optionsメソッドでthorコマンド実行時のオプションを指定できる
  • コマンドの引数を、メソッドの引数に渡すことが出来る
  • thor install path_to_file で、該当ファイル中で定義したthorメソッドをsystemに登録できる

設定例

class Setup < Thor  
    
  desc "config [NAME]", "copy configuration files"  
  method_options :force => :boolean  
  def config(name = "*")  
    # Config method body omitted.  
  end  
    
  desc "populate", "generate records"  
  method_options :count => 10  
  def populate  
    require './config/environment'  
    options[:count].times do |num|  
      puts "Generating article #{num}"  
      Article.create!(:name => "Article #{num}")  
    end  
  end  
end