Ruby on RailsのGeneratorの作り方。
script/generateでプラグインの雛形を作成する。
ruby script/generate plugin sample
Rails::Generator::NamedBaseを継承したSampleGeneratorクラスを作成する。
Rails::Generator::NamedBaseは、Rails::Generator::Baseを継承し、先頭の引数にクラス名を受け取る。
vendor/plugins/sample/generators/sample/sample_generator.rb
class SampleGenerator < Rails::Generator::NamedBase
次に、generatorに渡された引数を解釈する処理。
def initialize(runtime_args, runtime_options = {})
super #ここでクラス名が解釈される
#ここからは必要な引数やオプションを解釈する処理を自分で書く
end
Rails::Generator::NamedBase#initializeで引数が解釈され、
先頭の引数であるクラス名は、インスタンス変数に格納される。
2番目以降の引数は@argsに格納される。
引数であるクラス名が「HogeHoge::Foo::Bar」と「hoge_hoge/foo/bar」のときの、インスタンス変数の値。
- @name 先頭の引数であるそのままのクラス名(“HogeHoge::Foo::Bar”,”hoge_hoge/foo/bar”)
- @class_path Railsの命名規則に合わせたモジュール名の配列([“hoge_hoge”, “foo”])
- @file_path ファイルのパス(“hoge_hoge/foo/bar”)
- @class_nesting モジュール名(“HogeHoge::Foo”)
- @class_nesting_depth モジュール数(2)
- @class_name_without_nesting 命名規則に従ったクラス名(“Bar”)
- @singular_name 命名規則に従ったファイル名(“bar”)
- @plural_name @singular_nameの複数形(“bars”)
- @table_name モデルのテーブル名(hoge_hoge/foo_bars)
- @class_name クラス名(“HogeHoge::Foo::Bar”)
- @file_name @singular_nameの別名
- @actions @argsの別名
manifest()メソッドに、やりたい処理を書く。
def manifest
record do |m|
#ここにgeneratorでやりたい処理を書く
end
end
manifestの書き方は、「Generatorプラグインの作り方」の説明が詳しい。