Skip to content

Instantly share code, notes, and snippets.

@igravious
Created June 13, 2012 19:30
Show Gist options
  • Save igravious/2925939 to your computer and use it in GitHub Desktop.
Save igravious/2925939 to your computer and use it in GitHub Desktop.
Sexier migrations in Camping?
# put the following into safe_ar.rb our hack ar.rb or whatever takes your fancy
$SAFE_AR_EXTRAS = %{
# really, assumption is a terrible name
def self.schemify(assumption)
unless SchemaInfo.table_exists?
ActiveRecord::Schema.define do
create_table SchemaInfo.table_name do |t|
t.column :version, :float
end
end
end
SchemaInfo.find(:first) || SchemaInfo.new(:version => assumption)
end
def self.safe_create_schema(opts = {})
opts[:assume] ||= 0
opts[:version] ||= @final
if @migrations
si = schemify(opts[:assume])
if si.version < opts[:version]
got_to = nil
begin
@migrations.sort_by { |m| m.version }.each do |k|
got_to = k
k.migrate(:up) if si.version < k.version and k.version <= opts[:version]
k.migrate(:down) if si.version > k.version and k.version > opts[:version]
end
# this is a boolean
si.update_attributes(:version => opts[:version])
rescue => e
# print the message and return where we got to
$L.error { e.message }
got_to
end
end
end
end
}
Camping::Apps.each do |c|
c::Models.module_eval $SAFE_AR_EXTRAS
end
# once you have required safe_ar.rb
# change MyCampingApp to your camping app :)
begin
baseline = MyCampingApp::Models.schemify(0)
# $L.debug "Baseline version is #{baseline.version}"
what = MyCampingApp::Models.safe_create_schema
if what.respond_to?(:down)
# $L.debug "Rewinding Schema to last good point due to errors"
migrations = Models.instance_variable_get("@migrations")
# how to reverse sort_by ?
migrations.sort_by { |m| m.version }.reverse.each do |k|
k.migrate(:down) if what.version > k.version and k.version > baseline.version
end
# how to bail?
# send SIGINT ???
throw :halt, self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment