joe
joe

Reputation: 237

Rake task identifying the environment as development ruby and sinatra

I have written a scheduler using "whenever gem". one of my scheduler runs a rake task everyday. This rake task calls a method in my model and performs activerecord operations.

everything works fine, but the activerecord connects to "development" environment in the database.yml file and connects to development database while in production.

config/schedule.rb 

set :output, "log/cron_log.log"

every 6.hours do
  rake "sidekiq:restart"
end

every :day, :at => '01:00am' do
  rake 'prune_users:older_than_2months'
end

Rakefile

require 'newrelic_rpm'
require './app.rb'
import './lib/tasks/sidekiq.rake'
import './lib/tasks/reap_user.rake'
import './models/exportuser.rb'

/lib/tasks/reap_user.rake

require 'sinatra/activerecord'
require 'sinatra/activerecord/rake'

namespace :prune_users do

  desc 'Delete 2 months older users with status non-active'
  task :older_than_2months do
    ExportUser.delete_users_b4_2months
  end

end

/models/exportuser.rb

class ExportUser < ActiveRecord::Base
  self.table_name = 'exportusers'

  def self.delete_users_b4_2months
    begin
      @old_users = ExportUser.where("status != ? and Modified < ?", "Active", 2.months.ago)
      puts "Count of users before 2 months with non-active status on #{Time.now}"
      puts @old_users.count
      @old_users.find_each do |users|
        users.destroy!
      end
    rescue => err
      NewRelic::Agent.notice_error(err)
    end
  end

end

Everything works fine, but in ExportUser.rb, the activerecord connects to development database. How to make it connect to production.?

Upvotes: 1

Views: 724

Answers (2)

joe
joe

Reputation: 237

Add ENV['RACK_ENV']='production' in first line of rake task file "reap_users.rake" file before require 'sinatra/activerecord'. it worked fine :)

Upvotes: 0

mcfinnigan
mcfinnigan

Reputation: 11638

Your application should honour the RACK_ENV environment variable.

Try issuing the following command:

user@server $ RACK_ENV=production rake prune_users:older_than_2months

and verify whether it connects to the production database. If it does, you need to change whatever invokes your scheduled jobs to also include the RACK_ENV environment variable

Upvotes: 2

Related Questions