Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake before task hook

Tags:

ruby

rake

Is there a straight forward way to modify a Rake task to run some bit of code before running the existing task? I'm looking for something equivalent to enhance, that runs at the beginning rather than the end of the task.

Rake::Task['lame'].enhance(['i_run_afterwards_ha_ha'])
like image 735
bigtunacan Avatar asked Mar 29 '13 17:03

bigtunacan


People also ask

Where do I put rake tasks?

rake extension and are placed in Rails. root/lib/tasks . You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.

What are rake tasks used for?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.

How do you define a rake task?

Rake enables you to define a set of tasks and the dependencies between them in a file, and then have the right thing happen when you run any given task. The combination of convenience and flexibility that Rake provides has made it the standard method of job automation for Ruby projects.

How do you fail a rake task?

You can use abort("message") to gracefully fail rake task. It will print message to stdout and exit with code 1.


2 Answers

You can use the dependency of Rake task to do that, and the fact that Rake allows you to redefine existing task.

Rakefile

task :your_task do
  puts 'your_task'
end
task :before do
  puts "before"
end
task :your_task => :before

As result

$ rake your_task
before
your_task
like image 197
toch Avatar answered Sep 18 '22 12:09

toch


Or you could use the rake-hooks gem to do before and after hooks:

https://github.com/guillermo/rake-hooks

namespace :greetings do 
    task :hola    do puts "Hola!" end ;
    task :bonjour do puts "Bonjour!" end ;
    task :gday    do puts "G'day!" end ;  
end 

before "greetings:hola", "greetings:bonjour", "greetings:gday" do
  puts "Hello!"
end

rake greetings:hola # => "Hello! Hola!" 
like image 45
Chris Lewis Avatar answered Sep 16 '22 12:09

Chris Lewis