Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | Railsで自動生成しているコードのテンプレートを変更する

概要

Railsで自動生成しているコードのテンプレートを変更する

内容

Railsで自動生成しているコードのテンプレートを変更します。
まず以下のコマンドでテンプレートを出力出来ます。

rake rails:templates:copy

デフォルトのControllerテンプレート

lib/templates/controller/controller.rb

<% if namespaced? -%>
require_dependency "<%= namespaced_path %>/application_controller"

<% end -%>
<% module_namespacing do -%>
class <%= class_name %>Controller < ApplicationController
<% actions.each do |action| -%>
  def <%= action %>
  end
<%= "\n" unless action == actions.last -%>
<% end -%>
end
<% end -%>

クラスコメントとメソッドコメントを追加したControllerテンプレート

<% if namespaced? -%>
require_dependency "<%= namespaced_path %>/application_controller"

<% end -%>
<% module_namespacing do -%>
# <%= class_name %>
class <%= class_name %>Controller < ApplicationController
<% actions.each do |action| -%>
  # <%= action %>
  def <%= action %>
  end
<%= "\n" unless action == actions.last -%>
<% end -%>
end
<% end -%>

出力サンプル

自動生成実行

$ bundle exec rails g controller product index
      create  app/controllers/product_controller.rb
       route  get "product/index"
      invoke  haml
      create    app/views/product
      create    app/views/product/index.html.haml
      invoke  rspec
      create    spec/controllers/product_controller_spec.rb
      create    spec/views/product
      create    spec/views/product/index.html.haml_spec.rb
      invoke  helper
      create    app/helpers/product_helper.rb
      invoke    rspec
      create      spec/helpers/product_helper_spec.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/product.js.coffee
      invoke    scss
      create      app/assets/stylesheets/product.css.scss

出力されたcontroller
app/controllers/product_controller

# Product
class ProductController < ApplicationController
  # index
  def index
  end
end