#218 Making Generators in Rails 3
Generators in Rails 3 have been rewritten to use Thor which means the code used to create a generator is quite different. Here you will learn the new way to make generators in Rails 3.
- Download:
- source codeProject Files in Zip (95.2 KB)
- mp4Full Size H.264 Video (15 MB)
- m4vSmaller H.264 Video (10.4 MB)
- webmFull Size VP8 Video (28 MB)
- ogvFull Size Theora Video (20.9 MB)
Resources
- Episode 216: Generators in Rails 3
- Episode 58: How to Make a Generator
- Thor
- Full episode source code
bash
rails g generator --help
rails g generator layout
rails g layout --help
rails g layout admin
rails g layout foo --skip-stylesheet
rails g generator --help rails g generator layout rails g layout --help rails g layout admin rails g layout foo --skip-stylesheet
lib/generators/layout/layout_generator.rb
class LayoutGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
argument :layout_name, :type => :string, :default => "application"
class_option :stylesheet, :type => :boolean, :default => true, :desc => "Include stylesheet file."
def generate_layout
copy_file "stylesheet.css", "public/stylesheets/#{file_name}.css" if options.stylesheet?
template "layout.html.erb", "app/views/layouts/#{file_name}.html.erb"
end
private
def file_name
layout_name.underscore
end
end
class LayoutGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) argument :layout_name, :type => :string, :default => "application" class_option :stylesheet, :type => :boolean, :default => true, :desc => "Include stylesheet file." def generate_layout copy_file "stylesheet.css", "public/stylesheets/#{file_name}.css" if options.stylesheet? template "layout.html.erb", "app/views/layouts/#{file_name}.html.erb" end private def file_name layout_name.underscore end end
lib/generators/layout/templates/layout.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<%- if options.stylesheet? -%>
<%%= stylesheet_link_tag "<%= file_name %>" %>
<%- end -%>
<%%= javascript_include_tag :defaults %>
<%%= csrf_meta_tag %>
<%%= yield(:head) %>
</head>
<body>
<div id="container">
<%% flash.each do |name, msg| %>
<%%= content_tag :div, msg, :id => "flash_#{name}" %>
<%% end %>
<%%= yield %>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Untitled</title> <%- if options.stylesheet? -%> <%%= stylesheet_link_tag "<%= file_name %>" %> <%- end -%> <%%= javascript_include_tag :defaults %> <%%= csrf_meta_tag %> <%%= yield(:head) %> </head> <body> <div id="container"> <%% flash.each do |name, msg| %> <%%= content_tag :div, msg, :id => "flash_#{name}" %> <%% end %> <%%= yield %> </div> </body> </html>

