Skip to content

Instantly share code, notes, and snippets.

@akm
Created April 21, 2009 02:28
Show Gist options
  • Save akm/98896 to your computer and use it in GitHub Desktop.
Save akm/98896 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
require 'yaml/encoding'
class String
alias :old_to_yaml :to_yaml
def to_yaml(ops = {})
YAML.escape(self).old_to_yaml(ops)
end
end
require "yaml"
class String
def is_binary_data?
false
end
def decode
gsub(/¥¥x(¥w{2})/){[Regexp.last_match.captures.first.to_i(16)].pack("C")}
end
end
require 'yaml_waml'
ObjectSpace.each_object(Class){|klass|
klass.class_eval{
if method_defined?(:to_yaml) && !method_defined?(:to_yaml_with_decode)
def to_yaml_with_decode(*args)
result = to_yaml_without_decode(*args)
if result.kind_of? String
result.decode
else
result
end
end
alias_method :to_yaml_without_decode, :to_yaml
alias_method :to_yaml, :to_yaml_with_decode
end
}
}
namespace :db do
namespace :data do
desc "dump data from database for sharing among developers"
task :dump => :environment do
sql = "SELECT * from %s order by id"
skip_tables = ["schema_info", "schema_migrations", "schema_comments"]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "00000"
FileUtils.mkdir_p("#{RAILS_ROOT}/db/data")
File.open("#{RAILS_ROOT}/db/data/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
klass = Class.new(ActiveRecord::Base) do
set_table_name table_name
end
column_names = klass.columns.map(&:name)
column_order_modeule = Module.new do
def each_with_column_order(*args, &block)
@column_names.each do |column_name|
yield(column_name, self[column_name])
end
end
def self.extended(obj)
obj.instance_eval do
alias :each_without_column_order :each
alias :each :each_with_column_order
end
end
end
result = data.inject({}) do |hash, record|
record.instance_variable_set(:@column_names, column_names)
record.extend(column_order_modeule)
key = "#{table_name}_#{i.succ!}"
hash[key] = record
hash
end
result.instance_eval do
def each_with_order(*args, &block)
id_to_keys = {}
self.each_without_order do |key, value|
id = value['id'].to_i
id_to_keys[id] = key
end
id_to_keys.keys.sort.each do |id|
key = id_to_keys[id]
yield(key, self[key])
end
end
alias :each_without_order :each
alias :each :each_with_order
end
file.write result.to_yaml()
end
end
puts('dump finished.')
end
desc "load data to database for sharing among developers"
task :load => :environment do
require 'active_record/fixtures'
ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
(ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'db', 'data', '*.{yml,csv}'))).each do |fixture_file|
Fixtures.create_fixtures('db/data', File.basename(fixture_file, '.*'))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment