一般在我们想要的模块的文件夹名
(如: make_voteable)下有:
1.想要生成的放在模板文件的文件夹: templates
2.放置rails generate xxx 命令的文件(如:make_voteable_generator.rb)
在‘放置rails generate xxx 命令的文件‘通常有require 'rails/generators/想要的命令
一般为:
autoload :Actions, 'rails/generators/actions'
autoload :ActiveModel, 'rails/generators/active_model'
autoload :Migration, 'rails/generators/migration'
autoload :NamedBase, 'rails/generators/named_base'
autoload :ResourceHelpers, 'rails/generators/resource_helpers'
autoload :TestCase, 'rails/generators/test_case'
这里面的一个或几个。你想生成什么类型的文件??
而模板文件比较‘死’,一般来说你想要什么就写什么即可。
(一般来说 rails 插件里的 generators 与其它代码是‘无关的’,也就是说它们是独立的。生成代码可以与其它代码完全没有联系!)
==== 分隔线 === 3个常用方法
在这xyz_generator.rb文件中一定有source_root(path=nil)
方法
source_root(path=nil) 方法源代码:
# File railties/lib/rails/generators/base.rb, line 25
def self.source_root(path=nil)
@_source_root = path if path
@_source_root ||= default_source_root
end
还有 migration_template(source, destination=nil, config={})
上方法经常用到,需记住!源代码为:
# Creates a migration template at the given destination. The difference
# to the default template method is that the migration version is appended
# to the destination file name.
#
# The migration version, migration file name, migration class name are
# available as instance variables in the template to be rendered.
#
# ==== Examples
#
# migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"
#
def migration_template(source, destination=nil, config={})
destination = File.expand_path(destination || source, self.destination_root)
migration_dir = File.dirname(destination)
@migration_number = self.class.next_migration_number(migration_dir)
@migration_file_name = File.basename(destination).sub(/\.rb$/, '')
@migration_class_name = @migration_file_name.camelize
destination = self.class.migration_exists?(migration_dir, @migration_file_name)
if !(destination && options[:skip]) && behavior == :invoke
if destination && options.force?
remove_file(destination)
elsif destination
raise Error, "Another migration is already named #{@migration_file_name}: #{destination}"
end
destination = File.join(migration_dir, "#{@migration_number}_#{@migration_file_name}.rb")
end
template(source, destination, config)
end
此外,还有这个copy_file(src, dest, preserve = false, dereference = true)
。这个为Ruby代码!