bar_1

contents_map

2018年12月21日金曜日

Thor ジェネレータ Generators

ジェネレータ Generators

Thorのすぐれた利用方法のひとつは, カスタムのコード・ジェネレータを作ることだ.
Thor::Group, Thor::Actions そしてERBテンプレート群とを組み合わせれば, これをとても簡単に実現できる (訳注: Thorはもともとrakeやsakeの代替えとして開発されていたようだ. ). ここに例を示そう:
A great use for Thor is creating custom generators. Combining Thor::Group,
Thor::Actions and ERB templates makes this very easy. Here is an example:
class Newgem < Thor::Group
  include Thor::Actions

  # もろもろの引数とオプションを定義する
  # Define arguments and options
  argument :name
  class_option :test_framework, :default => :test_unit

  def self.source_root
    File.dirname(__FILE__)
  end

  def create_lib_file
    template('templates/newgem.tt', "#{name}/lib/#{name}.rb")
  end

  def create_test_file
    test = options[:test_framework] == "rspec" ? :spec : :test
    create_file "#{name}/#{test}/#{name}_#{test}.rb"
  end

  def copy_licence
    if yes?("Use MIT license?")
      # source rootディレクトリでMITLICENSEファイルをコピーする
      # Make a copy of the MITLICENSE file at the source root
      copy_file "MITLICENSE", "#{name}/MITLICENSE"
    else
      say "Shame on you…", :red
    end
  end
end
thor -T を実行すると, このジェネレータの使い方を表示する. それは thor newgem NAME を読むはずだ. これはジェネレータを実行するのに, われわれはNAMEという引数を与えなければならないことを示している.
Doing a thor -T will show how to run our generator. It should read:
thor newgem NAME. This shows that we have to supply a NAME
argument for our generator to run.
create_lib_file はERBテンプレートのひとつを使っている. これはこのようになる:
The create_lib_file uses an ERB template. This is what it looks like:
class <%= name.capitalize %>
end
あなたがジェネレータの中で設定した引数たちは template が呼び出されたときに, 自動で渡される. その他のオプション詳細は ドキュメント を読んで確認せよ.
The arguments that you set in your generator will automatically be passed in
when template gets called. Be sure to read the documentation for more options.
ジェネレータを thor newgem devise で実行すると, ふたつのファイルが作られる: “devise/lib/devise.rb” と “devise/test/devise_test.rb” だ. その次にユーザは, (yes? メソッドを使ったプロンプトで) MITライセンスのファイルをコピーしたいかどうかたずねられる.
もしテスト・フレームワークを変えたいなら, オプションを: thor newgem devise --test-framework=rspec のように追加できる. これはふたつのファイル: “devise/lib/devise.rb” と “devise/spec/devise_spec.rb” を生成する.
Running the generator with thor newgem devise will create two files: “devise/lib/devise.rb”, and “devise/test/devise_test.rb”. The user will then be asked (via a prompt by the yes? method) whether or not they would like to copy the MIT License. If you want to change the test framework, you can add the option: thor newgem devise --test-framework=rspec.
This will generate two files: “devise/lib/devise.rb” and “devise/spec/devise_spec.rb”.

0 件のコメント:

コメントを投稿

何かありましたら、どうぞ: