How to implement generators for a plugin located a

2019-08-29 18:00发布

问题:

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?

回答1:

I would make it a gem. I've made generators using gems, but I don't know if the generators would still work with plugins.

If you are having difficulty with the command line, I am guessing that you don't need any argument. (If you need an argument, I could copy the provided templates, and if I needed some other argument I'd be lost, so my advise is limited to non-argument.)

I have a generator gem which generates migration files needed for another gem. It checks if the migration with a given root name (w/o the timestamp prefix) is in db/migrate, and otherwise creates it.

Here is my code. I think this example is the help you need.

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