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

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

最近经常有一些需求要在生产环境上跑脚本修复部分数据,于是动起脑筋来做一个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

共收到 3 条回复

rails 看起来挺那么 aglie 的。

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

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

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