Skip to content

A way to wrap the default thread executor #4

@ximus

Description

@ximus

a ruthlessly handy library thank you,

I make use of it to speed up generating database seeds in a rails app (db/seeds.rb) file.

as such:

users = [
  {
    display_name: 'John McTest',
    email: 'test@example.com',
    password: password,
  },
  # ...
].in_threads.with_progress('users').map do |entry|
  User.create!(entry)
end

In order to make use of database connections across threads, one needs to wrap each block with ActiveRecord::Base.connection_pool.with_connection.

For readability concerns, I would like to avoid sprinkling ActiveRecord::Base.connection_pool.with_connection throughout my seeds file.

Right now I use the following heavy handed global workaround:

require 'in_threads'

InThreads::Pool.class_eval do
  def run(&block)
    wrapped = ->{ ActiveRecord::Base.connection_pool.with_connection { block.call } }
    @queue.push(wrapped)
  end
end

I was wondering if there is a better, recommended way of handling this situation? Maybe a way to configure (or wrap) the default thread execution? Or if I could easily write a new in_db_threads helper that would behave like in_threads, but wrap with activerecord, but that seems impossible without monkey patching this gem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions