0

I am using Ruby on Rails 3.2.2. I have implemented a Something plugin (it is almost a gem, but is not a gem) and all related files are in the lib/something directory. Since I would like to automate code generation related to that plugin, I came up with Ruby on Rails Generators. So, for the Something plugin, I am looking for implementing my own generators in the lib/something directory.

How should I make that and what are prescriptions? That is, for example, what rails generate command line should be invoked to properly generate all needed files in the lib/something directory? generators would still work with plugins (not gem)? what are advices about this matter?

4

1 回答 1

0

我会把它变成一颗宝石。我已经使用 gems 制作了生成器,但我不知道生成器是否仍然可以与插件一起使用。

如果您在使用命令行时遇到困难,我猜您不需要任何参数。(如果您需要参数,我可以复制提供的模板,如果需要其他参数,我会迷路,所以我的建议仅限于非参数。)

我有一个生成器 gem,它可以生成另一个 gem 所需的迁移文件。它检查具有给定根名称(没有时间戳前缀)的迁移是否在 db/migrate 中,否则创建它。

这是我的代码。我认为这个例子是你需要的帮助。

class ItrcClientFilesGenerator < Rails::Generators::Base
  source_root(File.dirname(__FILE__) + "/../src")

  desc "Generator to create migrations for needed db tables"
  def create_itrc_client_files
    prefix = DateTime.now.strftime("%Y%m%d%H%M")

    existing_migrations =
      Dir.glob("db/migrate/*itrc*").map do |path|
        File.basename(path).gsub(/^\d*_/, '')
      end

    Dir.glob(File.dirname(__FILE__) + "/../src/*").sort.each_with_index do |src_filepath, index|
      src_filename = File.basename(src_filepath)

      unless existing_migrations.include?(src_filename.gsub(/^\d*_/, '')) then
        this_prefix = "#{prefix}#{'%02i' % index}_"
        dst_filename = src_filename.gsub(/^\d*_/, this_prefix)

        copy_file(src_filename, "db/migrate/" + dst_filename)
      end
    end
  end
end
于 2012-09-19T19:05:13.223 回答