1

I have some buttons to purge collections so it's easy to restore the website to pristine state during development/test, without even restarting the server.

How can I execute the content of seeds.rb inside a controller action ?

def purge
  if Rails.env.production?
    should_not_happen(severity: :armageddon)
  else
    # Well at least restore one admin account !
    User.all.each(&:destroy)
    regenerate_main_admin_accounts # Here I need to replay the content of `seeds.rb`
    redirect_to(admin_dashboard_path)
  end
end

Note : the contents of my seeds.rb file make extensive use of conditionals and methods that check for the presence of data, I could run it a billion times there would be no duplicated data in the DB, so I can just run it even if only to restore 1% of what is gone (we're talking dev/test environments here, no time/resource pressure).

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

1

Assuming you're aware that this isn't a good idea, and it may involve security concerns, you can use Rake::Task["<rake_command>"].execute

Where <rake_command> is the statement you'd run after rake from the command line.

require 'rake'
require 'rake/task'

# We want to make sure tasks are loaded without running them more than once:
Rake::Task.clear  
<AppName>::Application.load_tasks


class SeedsController < ApplicationController

   def run
     Rake::Task["db:seed"].execute

     redirect_to "/" # Or wherever...
   end

end

Out of curiosity, why do you want to do this?

Anthony E
  • 11,072
  • 2
  • 24
  • 44
  • I am limiting this use to dev/test environments. We are also using Amazon SES in Sandbox mode, so we only have a limited number of email addresses that will work, and to test again our subscription processes/flow it's just so convenient to wipe collections. FactoryGirl factories also become quite handy when we need to test creation of new objects fast (atm we don't have many automated tests, and some people test manually) – Cyril Duchon-Doris Apr 13 '16 at 22:57
  • Thanks for your answer. In the end I have exported the code and the requires to a specific method of an utility module. – Cyril Duchon-Doris Apr 17 '16 at 14:41