RailsのカスタムGeneratorを自分で作る
事前に用意したテンプレートを基にファイルを生成するようなコマンドを作る。
今回はGemにしたいのでプラグイン作成の想定でやる。
Railsプラグイン作成環境を用意
bin/rails plugin new sampleplugin
gemspecファイルのTODOになってるところを書き換えて、bundle install
をする。
プラグイン自体はlib
ディレクトリ以下に作っていき、
test/dummy
にrailsプロジェクトがあるのでそこで動作確認をしていく。
Generatorクラスを作る
lib/generators/sample_generator.rb
にgeneratorの処理を記述する
class SampleGenerator < Rails::Generators::Base def initialize(args, *options) super @_args, @_options = args, options end def main # ここに処理を書く end end
これでbin/rails generate sample
などと叩くとmainが実行される。
テンプレートの用意
例えば
<%= @type_name %> = GraphQL::ObjectType.define do name '<%= @model_name %>' end
lib/generators/templates/types.rb
にこんな感じでファイルを作っておく。
テンプレートを使う
class SampleGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def initialize(args, *options) super @type_name ='sample_type' @model_name = 'Sample' end def main template "types.rb", "app/graphql/types/#{@type_name}.rb" end end
できた。