Search code examples
ruby-on-rails-4rakerake-taskmongoid4

How to drop all databases located in mongoid.yml from rake task?


I want to drop all database sessions which located in mongoid.yml from rake task. I am using rails4 and mongoid4. Here is my mongoid.yml:

development:
  sessions:
    default:
      database: cp1_dev
      hosts:
        - localhost:27017
    affiliate:
      database: cp2_dev
      hosts:
        -  localhost:27017
    shortener:
      database: cp3_dev
      hosts:
        -  localhost:27017

test:
  sessions:
    default:
      database: lion_test
      hosts:
        - localhost:27017
      options:
        read: primary
        max_retries: 1
        retry_interval: 0
    affiliate:
      database: cp_test
      hosts:
        -  localhost:27017
    shortener:
      database: cp1_test
      hosts:
        -  localhost:27017

When I execute rake db:drop or rake db:mongoid:drop commands they only drop the default database. So I have searched for it and find a solution which runs perfectly on rails console.

After the execution of rails console I simply put the following code on the console and hit the enter.

::Mongoid::Threaded.sessions.values.each do |session|
    p session.drop 
end 

As I said this is working like a charm on rails console. But when I inject this code to any rake task it does not work.

namespace :human do
  desc 'Resets databases'
  task :reset => :environment do
  ::Mongoid::Threaded.sessions.values.each do |session| 
       p session.drop 
  end
end

What is the proper way to let that code work for any rake task?


Solution

  • With the below workaround I can drop all mongoid sessions.

    mongoid = YAML.load_file('config/mongoid.yml')
    mongoid[Rails.env]["sessions"].each do |session|
      ::Mongoid::Sessions.with_name(session[0].to_sym).drop
    end