使用 rails 2.2.2 自带的 scaffold 生成带命名空间的脚本架时(如 Admin::Product),scaffold 会生成带命名空间的model(app/models/admin/product.rb),并且生成的 controller 代码看起来也很怪异,不能工作,想到后面还有那么多 scaffold 要生成,一个一个手动改实不在符合 DRY 精神,So, 写个脚本做些自动清理调整的工作看来相当有必要。

when running scaffold came with rails 2.2.2 with namespace(i.e. Admin::Product), it generates new model with namespace(app/models/admin/product.rb) and controller code looks wierd, which normally you didn’t expect it, this script done some fixing for u

环境 Env ruby 1.8.7 / gems 1.3 / rails 2.2.2

注意 Notice 脚本只能在 rails app 的根目录下运行 this script can only run in rails app root directory.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env ruby
require 'rubygems'
require 'active_support/inflector'

include ActiveSupport

scaffold = ARGV[0]
puts `script/generate scaffold #{scaffold}`
if scaffold =~ /::|//
  puts `script/destroy model #{scaffold}`
  path = Inflector.underscore(Inflector.pluralize(scaffold))
  full_class_name = Inflector.camelize(Inflector.singularize(path))
  class_name = Inflector.demodulize(full_class_name)
  model = Inflector.underscore(class_name)
  models = Inflector.pluralize(model)
  controller_path = "app/controllers/#{path}_controller.rb"
  code = File.open(controller_path, 'r') {|f| f.read}
  wrong_path = path.gsub('/', '_')
  code.gsub!(//#{wrong_path}/, '/'+path)
  code.gsub!(/@#{wrong_path}/, '@'+models)
  code.gsub!(/#{full_class_name}(W)/, class_name+'1')
  code.gsub!(/redirect_to(@#{model})/, "redirect_to(['#{File.dirname(path)}', @#{model}])")
  File.open(controller_path, 'w') {|f| f.write code}
end