Mark
Mark

Reputation: 6455

RoR - MySQL - Writing a rake task to inherit from another sql file

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.

Upvotes: 0

Views: 451

Answers (2)

maicher
maicher

Reputation: 2745

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

Upvotes: 2

spickermann
spickermann

Reputation: 107077

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

Upvotes: 3

Related Questions