Module: AktionTestRails::Support::Rails::ModelBuilder

Defined in:
lib/aktion_test_rails/support/rails/model_builder.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(example_group) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/aktion_test_rails/support/rails/model_builder.rb', line 5

def self.included(example_group)
  example_group.class_eval do
    before do
      @created_tables ||= []
    end

    after do
      drop_created_tables
    end
  end
end

Instance Method Details

#create_table(table_name, options = {}, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/aktion_test_rails/support/rails/model_builder.rb', line 17

def create_table(table_name, options = {}, &block)
  connection = ActiveRecord::Base.connection

  begin
    connection.execute("DROP TABLE IF EXISTS #{table_name}")
    connection.create_table(table_name, options, &block)
    @created_tables << table_name
    connection
  rescue Exception => e
    connection.execute("DROP TABLE IF EXISTS #{table_name}")
    raise e
  end
end

#define_model(name, columns = {}, &block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/aktion_test_rails/support/rails/model_builder.rb', line 35

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

#define_model_class(class_name, &block) ⇒ Object



31
32
33
# File 'lib/aktion_test_rails/support/rails/model_builder.rb', line 31

def define_model_class(class_name, &block)
  define_class(class_name, ActiveRecord::Base, &block)
end

#drop_created_tablesObject



48
49
50
51
52
53
54
# File 'lib/aktion_test_rails/support/rails/model_builder.rb', line 48

def drop_created_tables
  connection = ActiveRecord::Base.connection

  @created_tables.each do |table_name|
    connection.execute("DROP TABLE IF EXISTS #{table_name}")
  end
end