RailsのカスタムGeneratorを自分で作る

事前に用意したテンプレートを基にファイルを生成するようなコマンドを作る。

今回はGemにしたいのでプラグイン作成の想定でやる。

Railsプラグイン作成環境を用意

bin/rails plugin new sampleplugin

gemspecファイルのTODOになってるところを書き換えて、bundle installをする。

プラグイン自体はlibディレクトリ以下に作っていき、 test/dummyrailsプロジェクトがあるのでそこで動作確認をしていく。

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

f:id:anoChick:20170118032812p:plain

できた。