2016年2月27日 星期六

Making Generators in Rails 


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:description => "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

every public method in the class (Rails::Generators::Base) will be executed when the generator runs

  • arguments optional:  we can define a default value for each argument. We’ll add a layout_name argument with a default value of application
  • template method: which takes similar arguments to copy_file but which will parse any erb in the template before copying it to the destination directory
  • class_option: the ability to pass an option that will stop the stylesheet file being generated. We can do this by using the class_option method







沒有留言:

張貼留言