Skip to content

Instantly share code, notes, and snippets.

@skorbut
Created March 19, 2014 14:05
Show Gist options
  • Save skorbut/9642306 to your computer and use it in GitHub Desktop.
Save skorbut/9642306 to your computer and use it in GitHub Desktop.
Provide truncate and destroy_all support through cequel
class KeyspaceHelper
attr_reader :connection
def initialize
@connection = Cequel::Record.connection
end
def destroy_all
for_all_cequel_records do |clazz|
clazz.destroy_all
end
end
def truncate_all
for_all_cequel_records do |clazz|
truncate_table(clazz)
end
end
private
def for_all_cequel_records
Dir.glob(Rails.root.join('app', 'models', '**', '*.rb')).each do |file|
watch_stack = ActiveSupport::Dependencies::WatchStack.new
watch_stack.watch_namespaces([Object])
require_dependency(file)
new_constants = watch_stack.new_constants
if new_constants.empty?
new_constants << File.basename(file, '.rb').classify
end
new_constants.each do |class_name|
begin
clazz = class_name.constantize
rescue NameError
else
if clazz.ancestors.include?(Cequel::Record)
yield(clazz) if block_given?
end
end
end
end
end
def truncate_table(clazz)
connection.schema.truncate_table(clazz.table_name)
end
end
@elado
Copy link

elado commented Jul 25, 2014

For tests (RSpec/DatabaseCleaner) this is a faster version:
https://gist.github.com/elado/c95a4ffa952809865ee8

@skorbut
Copy link
Author

skorbut commented Jul 30, 2014

Record.descendants returns an empty list, if the models are not loaded, which is the case in my development and test environment. Collecting the created models in after_create is indeed a good idea to overcome some problems we have with destroy_all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment