Search code examples
ruby-on-railsrefactoringrake-taskrubocopruby-style-guide

rubocop eval in rake task


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.


Solution

  • 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