LoginSignup
38
41

More than 5 years have passed since last update.

rails g scaffold のカスタマイズ

Posted at

参考: http://guides.rubyonrails.org/generators.html

テンプレートのカスタマイズ

rake -T では出てこないけど、下記のタスクを使う

rake rails:templates:copy

すると下記のファイルが生成される。

lib
└── templates
    ├── erb
    │   ├── controller
    │   │   └── view.html.erb # rails g controlle で使われる
    │   ├── mailer
    │   │   └── view.text.erb # rails g mailer で使われる
    │   └── scaffold
    │       ├── _form.html.erb
    │       ├── edit.html.erb
    │       ├── index.html.erb
    │       ├── new.html.erb
    │       └── show.html.erb
    └── rails
        ├── assets
        │   ├── javascript.js
        │   └── stylesheet.css
        ├── controller
        │   └── controller.rb # rails g controller で使われる
        ├── helper
        │   └── helper.rb
        └── scaffold_controller
            └── controller.rb

上でコメントしたもの以外は rails g scaffold で使用される。
ここでたとえば lib/templates/scaffold/show.html.erb を変更すれば次に rails g scaffold した際に反映される。

Haml を生成

scaffold で Haml を生成する場合 generator をつくる必要がある (rake rails:templates:copy は必要ない)。

rails g generator haml/scaffold
lib
└── generators
    └── haml
        └── scaffold
            ├── USAGE
            ├── scaffold_generator.rb
            └── templates

scaffold_generator.rb を下記のように修正する。

require "rails/generators/erb/scaffold/scaffold_generator"
# erb 用の generator を継承する
class Haml::ScaffoldGenerator < Erb::Generators::ScaffoldGenerator
  source_root File.expand_path('../templates', __FILE__)

  protected
  def handler
    :haml
  end
end

lib/generators/haml/scaffold/templates 下に _form.haml, edit.haml, index.haml, new.haml, show.haml を用意する。

これらは erb として評価される。rake rails:templates:copy で生成される lib/templates/erb/scaffold/*.html.erb を参考に。

config/application.rb で、使用する generator を指定する。

# config/application.rb
module Foo
  class Application < Rails::Application
    config.generators do |g|
      g.template_engine :haml
      # 下記も指定しておくと無駄な helper / js / css が生成されない
      # g.helper false
      # g.stylesheets false
      # g.javascripts false
    end
    # ...
  end
end
38
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
41