Skip to content

Instantly share code, notes, and snippets.

@jferris
Created August 3, 2009 19:40
Show Gist options
  • Save jferris/160789 to your computer and use it in GitHub Desktop.
Save jferris/160789 to your computer and use it in GitHub Desktop.
module ModelBuilder
def self.included(spec)
spec.before(:each) do
@created_tables = []
@defined_constants = []
end
spec.after(:each) { undefine_constants }
spec.after(:each) { drop_created_tables }
spec.send(:include, Helpers)
end
module Helpers
def create_table(table_name, &block)
connection = ActiveRecord::Base.connection
begin
connection.execute("DROP TABLE IF EXISTS #{table_name}")
connection.create_table(table_name, &block)
@created_tables ||= []
@created_tables << table_name
connection
rescue Exception => e
connection.execute("DROP TABLE IF EXISTS #{table_name}")
raise e
end
end
def define_constant(class_name, base, &block)
class_name = class_name.to_s.camelize
klass = Class.new(base)
Object.const_set(class_name, klass)
klass.class_eval(&block) if block_given?
@defined_constants ||= []
@defined_constants << class_name
klass
end
def define_model_class(class_name, &block)
define_constant(class_name, ActiveRecord::Base, &block)
end
def define_model(name, columns = {}, &block)
class_name = name.to_s.pluralize.classify
table_name = class_name.tableize
create_table(table_name) do |table|
columns.each do |name, type|
table.column name, type
end
end
define_model_class(class_name, &block)
end
def undefine_constants
@defined_constants.each do |class_name|
Object.send(:remove_const, class_name)
end
end
def drop_created_tables
@created_tables.each do |table_name|
ActiveRecord::Base.
connection.
execute("DROP TABLE IF EXISTS #{table_name}")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment