我只是想创建一个没有任何参数的插件迁移生成器,例如:$railsgenerate yaffle
,这应该复制迁移文件(lib/generators/yaffle/template/create_yaffle.rb)到 db/migrate/[时间戳]_create_yaffle.rb。
- 我在这里面临的问题是,它的复制,但没有时间戳。
- 此外,当我运行
$railsgenerate yaffle
时,它会向我显示一条消息,指出未提供参数,它预计采用以下格式railsgenerate yaffle NAME [options]
。我不想有任何选项/参数,它应该只是railsgenerate yaffle
。
我应该做什么?
我跟踪了 acts_as_commentable 中使用的生成器,看起来很简单,但我不知道在哪里修改这些设置...有人可以帮忙吗?
生成器代码:
require 'rails/generators'
require 'rails/generators/migration'
class ThumbitGenerator Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def self.next_migration_number(path)
Time.now.utc.strftime("%Y%m%d%H%M%S")
end
def create_model_file
template "like.rb", "app/models/like.rb"
template "liking.rb", "app/models/liking.rb"
template "create_likes.rb", "db/migrate/create_likes.rb"
template "create_likings.rb", "db/migrate/create_likings.rb"
end
end
最佳答案
好的,我找到了答案...
- 我在生成器文件中使用了
Rails::Generators::NamedBase
而不是Rails::Generators::Base
!当您使用 NamedBase 时,它总是期望传递一个参数(这是初始化程序的名称) - 我使用的是
template
方法而不是migration_template
,因为迁移文件不会生成任何迁移编号
最后,这成功了!
require 'rails/generators'
require 'rails/generators/migration'
class ThumbitGenerator < Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
def self.next_migration_number(path)
Time.now.utc.strftime("%Y%m%d%H%M%S")
end
def create_model_file
template "like.rb", "app/models/like.rb"
template "liking.rb", "app/models/liking.rb"
migration_template "create_likes.rb", "db/migrate/create_likes.rb"
migration_template "create_likings.rb", "db/migrate/create_likings.rb"
end
end
关于ruby-on-rails - 插件中的生成器和迁移 (rails 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4141739/