自己写个gem叫change_log 水平有限欢迎斧正

这几天把公司项目上的一些东西整理了整理,把能单独拿出来的东西都拿出来。写成gem,这样公司其他的项目就可以方便使用了。

change_log,也叫maintenance log. 意思就是保存所有表中数据的修改。包括谁在什么时间创建/修改/删除了哪些东西。

应用环境:

例如,公司有个会计系统。如果哪天你看见有一个账目变的非常奇怪,好像跟你之前看到的不大一样。
可以调出所有的change_log。一看,原来是小谁家的小谁把某个数改了。找到了元凶。

可能应用面不是很广,但是放在这里还是请大家斧正斧正。

rubygems 里面有类似的gem. 在这里我不想讨论谁抄了谁的理念。

只想把自己的东西越弄越好,说不定能帮助其他人。

谢谢

下面是用法:

1 安装:

# console window
gem install change_log

# environment.rb
config.gem 'change_log'

或者 用 bundler

# Gemfile
gem 'change_log'

# console window
bundle install


2. Database Table
创建一个migration file:
注意: 名字可以随便起,只要在environment.rb里面重新声明就可以。


class AddChangeLog < ActiveRecord::Migration
def self.up
create_table :change_logs do |t| # feel free to choose another table name
t.integer :version, :null=>false # store version of each change
t.string :record_id,:limit=>30 # store the actual record id
t.string :table_name, :limit=>60 # store the table name
t.string :attribute_name,:limit=>60 # store the column name
t.string :user, :limit=>20 # store the user who made the change
t.string :action, :limit=>6 # store the change action: create, read, update, delete
t.text :old_value # the value before change
t.text :new_value # value after change
t.string :field_type, :limit=>30 # the column type eg. date, text, varchar, int etc
t.timestamps
end
end

def self.down
drop_table :change_logs
end
end



然后:

#console window
db:migrate


3. 应用
在你想要保存修改记录的model里加上这个:

enable_change_log :ignore=>[:updated_at,:user_password]

用ignore来声明那些不想被保存的column.


在application controller 里加一个current_user 方法:

def current_user
return session[:user] # replace this with your own code
end


这样的话,在controller 和helper里面的所有CRUD都会被记录下来。


如果,你在model中进行修改的话。 例如:

# this is a model file
def making_some_changes
user = User.find(:first)
user.website = 'www.iteye.com'
user.save
end


你可以用whodidit这个属性。这个是change_log自动添加进去的。

# this is a model file
def making_some_changes
user = User.find(:first)
user.website = 'www.iteye.com'
user.whodidit = 'javaeye' # 这样就可以了
user.save
end



4. 列出已经保存的修改记录

用 ChangeLogs model,来调用修改记录。


# List all changes
ChangeLogs.find(:all)

# List all changes for table 'accounts'
ChangeLogs.find(:all,:conditions=>['table_name = ?', 'accounts'])



5. 如果你想用别的表名。 那就修改migration文件。
然后在environment.rb里面声明:

# config/environment.rb
ChangeLogs.set_table_name('maintenance_logs')



6. 一些连接:

Rubygems: https://rubygems.org/gems/change_log

GitHub: https://github.com/peterzatncs/change_log

7. 参考资料

http://railscasts.com/episodes/245-new-gem-with-bundler

http://docs.rubygems.org/read/chapter/20


最后,欢迎任何批评和斧正。
我必须承认有很多地方还不足。光是一个Readme就修改了很多次。

再次感谢。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值