coolesting
coolesting

Reputation: 1451

How do I structure the file and directory Rake tasks within a regular task?

I want to generate the file my.db in the db/ directory. I'm unfamiliar with how to structure the file and directory tasks within a regular task. Help!

task :create, [:name, :type] do |t, args|
  args.with_defaults(:name => "mydb", :type => "mysql")
  directory "db"
  file "db/my.db" => "db" do
    sh "echo 'Hello db' > db/my.db"
  end
  puts "Create a '#{args.type}' database called '#{args.name}'"
end

Upvotes: 3

Views: 5684

Answers (1)

roboles
roboles

Reputation: 886

The following code will create the db and file unless the already exist...

You can use this if you wish to have the commands in a single rake task

Dir.mkdir("db") unless Dir.exists?("db")
unless File.exists?("db/my.db")
  File.open("db/my.db", 'w') do |f|
    f.write("Hello db")
  end
end

If you wish to use the file task provided by rake you would need to do this...

# Rakefile
directory "db"

file "db/my.db" => 'db' do
  sh "echo 'Hello db' > db/my.db"
end

task :create => "db/my.db" do 
end

In this example your actually telling rake to create tasks called "db" and "db/my.db" which have the side effect of creating the directory or file.

Hope this helps, sorry for the initial confusion :)

Upvotes: 14

Related Questions