原创作者: hideto   阅读:1091次   评论:0条   更新时间:2011-05-26    
今天看看怎么写自己的Generators
Rails在以下地方查找用户自定义的Generators:
RAILS_ROOT/lib/generators
RAILS_ROOT/vendor/generators
RAILS_ROOT/vendor/plugins/any_subdirectory/generators
~/.rails/generators
以及以_generator为后缀的Gems
我们看看一个例子代码:
class TumblepostGenerator < Rails::Generator::NamedBase
  def manifest
    record do |m|
      m.class_collisions class_name
      m.template  "app/controllers/controller_template.rb",
                  "app/controllers/#{file_name}_controller.rb"
      m.template  "app/models/model_template.rb",
                  "app/models/#{file_name}.rb"
      m.directory File.join('app/views', file_name)
      m.template  "app/views/form_template.rhtml",
                  "app/views/#{file_name}/_form.rhtml"
      m.template  "app/views/view_template.rhtml",
                  "app/views/#{file_name}/_view.rhtml"

      m.readme "POST_GENERATION_REMINDER"
    end
  end
end

其中Rails::Generator::NamedBase是ruby script/generator后面带参数的,而Rails::Generator::Base是不带参数的
生成的文件会先用ERB解析,这样我们可以自己构建生成文件的模板,如:
class <%= class_name %>Controller < TumblepostController
  def new
    @thing = <%= class_name %>.new
  end

如果我们要生成数据库Migration,我们可以这样写:
m.migration_template "db/migrations/migration_template.rb", "db/migrate"

事实上已经有很多Generators创建好并以gems部署了,让我搜索一下:
gem search -r generator
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics