3

In my rails project (Rails 3.1, Ruby 1.9.3) there are around 40 rake tasks defined. The requirement is that I should be able to create an entry (the rake details) in a database table right when we start each rake. The details I need are the rake name, arguments, start time and end time. For this purpose, I don't want rake files to be updated with the code. Is it possible to do this outside the scope of rake files.

Any help would be greatly appreciated!!

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
Anoob K Bava
  • 598
  • 7
  • 19
  • You can provide hook to your rake tasks : http://stackoverflow.com/questions/15707940/rake-before-task-hook. Howeber, I am not sure you can access the rake name/arguments of the task invoqued. – Raphael Pr Jul 20 '16 at 07:34

3 Answers3

0

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

For example in your Rakefile

require 'rake/hooks'

task :say_hello do
  puts "Good Morning !"
end

before :say_hello do
  puts "Hi !"
end

#For multiple tasks

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!"
Xeeshan
  • 156
  • 10
  • It does not solve my problem, i want a method to be executed before every rake with out existing my rake tasks – Anoob K Bava Jul 20 '16 at 08:33
  • We need to move our rake task in a name space and in before hook just called your method. You don't need to update your existing tasks, but you need to update rake file to add namespace and before hook. – Xeeshan Jul 20 '16 at 09:17
  • seems to be okay , but my requirement is that , one method should be called irrespective of every rake task in the lib/tasks. if added a new new rake task, it should be called this method. But this hooks should be active only for the mentioned tasks in the rake file. The main aim is to record the rake task name, arguments, and its start and end time to a database table. – Anoob K Bava Jul 20 '16 at 11:19
0

This seems to be a bit awkward, But it may help others.

Rake.application.top_level_tasks

will return an array of information including Rake name and its arguments. Reference attached below.

pry(main)> a = Rake.application.top_level_tasks
=> ["import_data[client1,", "data.txt]"]
Anoob K Bava
  • 598
  • 7
  • 19
-1

When you create rake task, you can pass a parent task which will run before your task:

task my_task: :my_parent_task do
  # ...
end

If your task depends from more than 1 task, you can pass an array of parent tasks

task my_task: [:my_prev_task, :my_another_prev_task] do
  # ...
end
Twizty
  • 102
  • 3
  • i dont want to update my existing rake tasks. What i need is only a common point which can be called before every tasks – Anoob K Bava Jul 20 '16 at 07:24