Module: ActiveRecordTemptable

Extended by:
ActiveRecordTemptable
Included in:
ActiveRecordTemptable
Defined in:
lib/active_record_temptable.rb,
lib/active_record_temptable/version.rb

Constant Summary collapse

DEFAULT_TABLE_NAME =
'activerecord_temptable_records'.freeze
VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#create_indexes(connection, table_name, indexes) ⇒ void

This method returns an undefined value.

Calls add_index for every element in array

Parameters:

  • connection (ActiveRecord::ConnectionAdapters)
  • table_name (String)
  • indexes (Array)

49
50
51
52
53
# File 'lib/active_record_temptable.rb', line 49

def create_indexes(connection, table_name, indexes)
  indexes.each do |fields, options|
    connection.add_index(table_name, fields, options || {})
  end
end

#create_table(connection, relation, table_name) ⇒ void

This method returns an undefined value.

Creates temp table and loads provided relation into it

Parameters:

  • connection (ActiveRecord::ConnectionAdapters)
  • relation (ActiveRecord::Relation)
  • table_name (String)

    name of table


39
40
41
# File 'lib/active_record_temptable.rb', line 39

def create_table(connection, relation, table_name)
  connection.execute(new_table_command(relation, table_name))
end

#with_temptable(relation, indexes = [], table_name = DEFAULT_TABLE_NAME) ⇒ void

This method returns an undefined value.

Yields provided relation loaded in temporary table

Parameters:

  • relation (ActiveRecord::Relation)
  • indexes (Array) (defaults to: [])

    add_index will be called for every element in indexes

  • table_name (String) (defaults to: DEFAULT_TABLE_NAME)

    name of table


18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/active_record_temptable.rb', line 18

def with_temptable(relation, indexes = [], table_name = DEFAULT_TABLE_NAME)
  ActiveRecord::Base.connection_pool.with_connection do |connection|
    connection.transaction do
      begin
        create_table(connection, relation, table_name)
        create_indexes(connection, table_name, indexes) if indexes.any?
        klass = relation.klass
        yield klass.unscoped.from("#{table_name} AS #{klass.table_name}") if block_given?
      ensure
        connection.drop_table(table_name, if_exists: true)
      end
    end
  end
end