Rails 写了个在 Production 上跑脚本的 Helper

gene_wu · 2013年01月31日 · 最后由 gene_wu 回复于 2013年02月01日 · 2578 次阅读

最近经常有一些需求要在生产环境上跑脚本修复部分数据,于是动起脑筋来做一个 DSL。可以跑脚本的时候有一些交互,并支持各种参数(谁叫咱们号称 SAAS 公司)。

我丢到 github 上去了以供大家鄙视。贴个 README.MD 在这里。

rails_db_script_helper

This is a single file helper to make your script easy to be written and read. I used it in my daily job.

Principal

  • Single File to apply minimalism
  • No dependency except std lib / Rails
  • Command Line parameter friendly
  • Optional Prompty for opitons
  • Confirm before submit transaction

Example Script

require File.join(File.dirname(__FILE__), '..', 'db_script_helper')

# script topic and detail description
desc "User Fix", "Propose : Fix user data if user is invalid" do 

  # require parameter of company id, if passed by parameters, will ignore prompty
  param :company, "Company ID", :required => true

  # you can define different data set to update
  change_set :invalid_users do
    #return could be one record or array of record
    User.find_all_by_company_id params[:company]
  end

  # update data set you asked
  update :invalid_users do |rec|
    rec.is_deleted = true
  end
  # it will show all change set and confirm with Y/N

  # a summary is a good change data report
  summary :invalid_users do |result|
    puts result
  end
end

Execution

cd rails_app_path script/runner example_path.rb [options]

Example Output

================================================================================ User Fix ================================================================================ Propose : Fix user data if user is invalid ================================================================================ Company ID : 12 ================================================================================ Processing ================================================================================ users : 36 +-is_deleted : false -> true users : 40 +-is_deleted : false -> true users : 84 +-is_deleted : false -> true users : 85 +-is_deleted : false -> true users : 86 +-is_deleted : false -> true ================================================================================ [Y]es / [N]o :N ================================================================================ QUIT without changing ================================================================================

移驾 github 索取代码 https://github.com/genewoo/rails_db_script_helper

rails 看起来挺那么 aglie 的。

#2 楼 @xdite cape 挺好的,学习了。

这个 helper 也是我学习写类 rspec 的框架的产物,可惜我文笔不足,无法描述在这个过程中的一些心得,就 Open Source 出来大家提提意见

需要 登录 后方可回复, 如果你还没有账号请 注册新账号