Skip to content

Instantly share code, notes, and snippets.

@EastResident
Created November 23, 2016 08:32
Show Gist options
  • Save EastResident/221b15f3a0dd3d7c3726f9be210e428c to your computer and use it in GitHub Desktop.
Save EastResident/221b15f3a0dd3d7c3726f9be210e428c to your computer and use it in GitHub Desktop.
migrate -> ridgepole移行スクリプト
Dir::foreach('db/migrate/.') do |file|
next if file == '.' || file == '..'
state = 0
table = ''
table_name = ''
open("db\/migrate\/#{file}") do |f|
file_name = file.match(/.+_create_(\w+)\.rb/)[1]
wf = open("db\/schemas\/#{file_name}\.rb", 'w')
f.each do |line|
if line.include?('create_table')
state = 1
table_name = line.match(/\s*create_table\s+:(\w+)/)[1]
end
# referencesをidに置換
if line.include?('references')
ref = ''
if line.include?(',')
ref = line.match(/t.references\s+:(\w+)(,.+)/)
else
ref = line.match(/t.references\s+:(\w+)/)
end
table << " t\.integer :#{ref[1]}_id#{ref[2]}\n".sub(' ', '') if state == 1
table << " t\.index \[:#{ref[1]}_id\], name: 'index_#{table_name}_on_#{ref[1]}_id', using: :btree\n".sub(' ', '') if state == 1
else
table << line.sub(' ', '') if state == 1
end
if state == 1 && line.strip =='end'
state = 0
end
if line.include?('foreign_key')
ref = line.strip.match(/.+\,\s:(\w+)/)
table << "#{line.strip}, name: '#{table_name}_on_#{ref[1]}'\n"
elsif line.include?('add_index')
table << line.strip
table << "\n"
end
end
wf.print table
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment