Create YAML test fixtures from database

本文介绍了一种使用Rails框架从现有数据库中创建YAML测试样例的方法。通过简单的命令即可将数据库中的数据转换为YAML文件,特别适用于权限管理场景。
转于
[url]http://snippets.dzone.com/tag/yaml[/url]

[code]
运行:
cd #{RAILS_ROOT}/lib/tasks/
rake db:fixtures:dump_all
or
rake db:fixtures:dump_references


namespace :db do
namespace :fixtures do

desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
task :dump_all => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
ActiveRecord::Base.establish_connection(:development)
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "000"
File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end
end

namespace :fixtures do
desc 'Create YAML test fixtures for references. Defaults to development database.
Set RAILS_ENV to override.'
task :dump_references => :environment do
sql = "SELECT * FROM %s"
dump_tables = ["areas","countries"]
ActiveRecord::Base.establish_connection(:development)
dump_tables.each do |table_name|
i = "000"
file_name = "#{RAILS_ROOT}/test/fixtures/#{table_name}.yml"
p "Fixture save for table #{table_name} to #{file_name}"
File.open(file_name, 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end
end
end

[/code]
权限管理用下面方法直接把数据库中的数据导出。test 时非常方便。要不那么多权限输死人嘞。
[code]desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'


run:
cd #{RAILS_ROOT}/lib/tasks/
rake extract_fixtures

task :extract_fixtures => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "000"
File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值