0

I use the following command from terminal:

mysql -u root -p sample_development < sample.sql

Is there a simple way of me including this command in a rake task? I've found some old answers, Is there a rake task for backing up the data in your database?, which includes around 30 lines of code, but is there an easier way to translate this one liner into a rake task?

Thanks in advance.

Community
  • 1
  • 1
Mark
  • 6,112
  • 4
  • 21
  • 46
  • Why do you want to translate this simple command into a Rake task? What are you optimizing for? Would a `system` call or backticks be an option? – spickermann Apr 20 '17 at 09:25
  • There are a few setup instructions to be run before you can start using the app and we have a few people developing it - I"m trying to combine them all into one rake task that people can't mess up but if there is a way around it using any of your methods please let me know – Mark Apr 20 '17 at 09:27

2 Answers2

3

There are a few different ways to run command line instructions from Ruby. A very simple solution might look like this (note the backticks):

task :import do
  # some code
  `mysql -u root -p sample_development < sample.sql`
  # more code
end
Community
  • 1
  • 1
spickermann
  • 100,941
  • 9
  • 101
  • 131
2

You are asking for a rake task, but the link reffers to capistrano task. I'm guessing that you want to run your import locally, so the rake task is the way to go.

Rake tasks are written in Ruby. You can embed any shell command in ruby by using:

This is how the rake task could look like:

    # lib/tasks/db.rake
    namespace :db do
      task import: :environment do
        `mysql -u root -p sample_development < sample.sql`
      end
    end

Use it like:

    $ rake db:import
maicher
  • 2,625
  • 2
  • 16
  • 27