Showing posts with label share db. Show all posts
Showing posts with label share db. Show all posts

Tuesday, July 2, 2013

Delayed job to use specific connection via ruby

Hello Guys,
           Yesterday  i was phasing one interesting problem. Sharing single database between 2 rails application but now i've requirement to use application specific table for delayed jobs.

Lets assume i've application called DemoApp & TestApp. And both sharing single DB called 'demo_app_prod'. Now for TestApp i required separate DB called 'test_app_prod' which has single table called 'delayed_jobs'.

Step1:

at TestApp you have database.yaml like
 login: &login
  adapter: mysql
  username: admin
  host: localhost  

  password:
 
development:
  <<: *login
  database:
demo_app_dev

test:
  <<: *login
  database:
demo_app_test
 
production:
  <<: *login
  database:
demo_app_prod  

staging:
  <<: *login
  database: test_app_prod


Step2:
at TestApp added migration called 
   rails generate migration add_delayed_job

  class AddDelayedJob < ActiveRecord::Migration
  def connection
    ActiveRecord::Base.establish_connection(Rails.env).connection
  end

 
  def up
    oldEnv = Rails.env
    Rails.env = 'staging' #set environment variable from your database.yml
    ActiveRecord::Base.establish_connection(Rails.env) 
  
    create_table :delayed_jobs, :force => true do |table|
      table.integer  :priority, :default => 0 

      table.integer  :attempts, :default => 0  
      table.text     :handler                      
      table.text     :last_error                  
      table.datetime :run_at                       
      table.datetime :locked_at                    
      table.datetime :failed_at                    
      table.string   :locked_by          
      table.timestamps
    end
    Rails.env = oldEnv
    ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env]

  end
 
  def down   
    oldEnv = Rails.env
    Rails.env = '
staging'
    ActiveRecord::Base.establish_connection(Rails.env).connection

    drop_table :delayed_jobs
    Rails.env = oldEnv
    ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env]

  end
end


Step3:

 In initializers/delayed_job.rb add below lines

Delayed::Job.class_eval do
  establish_connection ActiveRecord::Base.configurations["local"]
end


This the easy way to establish multiple db connection via ruby for delayed job.