0

Rubocop chokes on the following setup:

desc 'Clear the db data of development records'
task clear: :environment do
  msg('Clearing the development database and rebuilding the default values')
  'job,company'.split(/, ?/).each do |model|
    # rubocop:disable all
    eval("#{model.capitalize}.destroy_all")
    # rubocop:enable all
  end
end

As you can I skipped the eval section for now so I can use this rake task, but I wonder if there is a better way to achieve this. As we expand the app and add more models I wanted to save time by appending them to the list.

Chris Hough
  • 3,389
  • 3
  • 41
  • 80

1 Answers1

2

Rubocop is complaining about eval. Are you trying to clear certain tables or the entire db?

To avoid the eval and keep doing it your way:

Use 'some_class_as_a_string'.classify.constanize. This will turn your string into the class you're looking for.

In your case, the solution is: model.classify.constantize.destroy_all

If you're trying to clear the entire database:

Running rake task rake db:migrate:reset clears the db for the current environment.

This post: How to run Rake tasks from within Rake tasks? covers calling a rake task from another rake task

It looks like you're trying to build a rake task to clear the db, then reseed it. This can be done using

rake db:migrate:reset && rake db:seed

Community
  • 1
  • 1
sbjluke
  • 309
  • 5
  • 15
  • I am only trying to clear certain tables. I use seeds to properly setup other tables that do not change so they do not need to be reset. – Chris Hough Feb 19 '16 at 01:54
  • Gotchya! Well I'd just stick with what you got. There may be something clever, but what you got works and it's simple. I'd choose it over adding some superfluous gem that does just that under the hood. – sbjluke Feb 19 '16 at 02:11
  • Hey @chrishough, just edited the answer with a better way to avoid the eval. Cheers! – sbjluke Feb 23 '16 at 21:27