Skip to content

Instantly share code, notes, and snippets.

@tizoc
Created August 24, 2011 16:11
Show Gist options
  • Save tizoc/1168417 to your computer and use it in GitHub Desktop.
Save tizoc/1168417 to your computer and use it in GitHub Desktop.
desc "migrate", "Runs Sequel migrations"
def migrate(version=nil, database_url=DATABASE_URL)
require 'sequel'
Sequel.extension :migration
db = Sequel.connect(database_url, :test => true)
puts 'Running migrations...'
Sequel::Migrator.apply(db, 'db/migrate', version && version.to_i)
dump_schema
end
desc "create_migration", "Creates a Sequel migration"
def create_migration(name, version=nil)
migrations_dir = File.join("db", "migrate")
version ||= Time.now.utc.strftime("%Y%m%d%H%M%S")
filename = "#{version}_#{name}.rb"
FileUtils.mkdir_p(migrations_dir)
open(File.join(migrations_dir, filename), 'w') do |f|
f << (<<-EOS).gsub(" ", "")
Sequel.migration do
change do
end
end
EOS
end
end
desc "dump_schema", "Generates db/schema.rb"
def dump_schema(database_url=DATABASE_URL,
schema_file="#{File.dirname(__FILE__)}/db/schema.rb")
require 'sequel'
Sequel.extension :schema_dumper
db = Sequel.connect(database_url, :test => true)
puts 'Dumping schema...'
open(schema_file, 'w') do |f|
f << db.dump_schema_migration(:same_db => false)
end
end
desc "dump_schema_image", "Generates doc/schema.png"
def dump_schema_image
require './init'
associations = []
classes = []
File.open('doc/schema.dot', 'w') do |out|
Sequel::Model.descendents.each do |c|
next if c.name.blank?
c.associations.each do |a|
ar = c.association_reflection(a)
begin
ac = ar.associated_class
rescue NameError
$stderr.puts "Couldn't get associated class for #{c}.#{ar[:type]} #{ar[:name].inspect}"
else
associations << [c.name, ar[:type], ac.name]
end
end
end
styles = {:many_to_one=>:bold, :one_to_many=>:solid, :many_to_many=>:dashed, :one_to_one=>:dotted}
out << "digraph G {\n"
out << associations.uniq.map{|c, t, ac| " #{c} -> #{ac} [style=#{styles[t]}];"}.sort.join("\n")
out << "\n}\n"
end
system('dot -Tpng doc/schema.dot > doc/schema.png')
puts 'Done.'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment