Created
March 19, 2014 14:05
-
-
Save skorbut/9642306 to your computer and use it in GitHub Desktop.
Provide truncate and destroy_all support through cequel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
For tests (RSpec/DatabaseCleaner) this is a faster version:
https://gist.github.com/elado/c95a4ffa952809865ee8
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
You can use
Cequel::Record.descendants
to get all models.