Created
July 18, 2014 22:02
-
-
Save jurikern/deb9c74a91ca8c9c9259 to your computer and use it in GitHub Desktop.
Using multiple connections within a single model (method)
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
# Use pipe to transfer data between fork and parent process | |
reader, writer = IO.pipe | |
# Fork process to isolate the work with multiple database connections from application | |
pid = fork do | |
reader.close() | |
begin | |
# if used Redis uncomment this line to reset connection | |
# REDIS = Redis.new(:host => '', :port => '', :password => '') | |
# In this point used application current database connections, :production | |
# Fetch data from your_db database | |
@model = YourModels.includes(:another_model).first | |
# Switch database connection, in this point start using :production_fork connection | |
ActiveRecord::Base.establish_connection :production_fork | |
@cloned_model = @model.dup | |
# Model has been saved with :production_fork connection | |
# Data has been saved in your_fork_db database | |
@cloned_model.save | |
writer.write(@cloned_model.id) | |
rescue Exception => e | |
print e.inspect | |
ensure | |
ActiveRecord::Base.remove_connection | |
# If used Redis uncomment this line to disconnect | |
# REDIS.client.disconnect if used | |
Process.exit! | |
end | |
end | |
Process.waitpid(pid, 0) | |
# In this point used again application current database connection, :production | |
writer.close() | |
# Print @cloned_model.id | |
print reader.read() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment