Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake task outside of namespace

I have a rake file set up like so:

require 'rake'

namespace :setup do
  puts "I'm in setup"
  task :create do
    puts "I'm in create"
  end
end

task :run do
  puts "I'm in run"
end

If I run rake setup:create I get the expected:

I'm in setup
I'm in create

However, if I run rake run I get:

I'm in setup
I'm in run

From what I can tell in the guides, this is unexpected as stated here:

When looking up a task name, rake will start with the current namespace and attempt to find the name there. If it fails to find a name in the current namespace, it will search the parent namespaces until a match is found (or an error occurs if there is no match).

Wouldn't that assume rake starts at the current namespace and then moves on looking for something. In my example, I don't provide a current namesapce yet it jumps into setup even though all I gave it was run.

What am I missing?

like image 470
Anthony Avatar asked Jan 06 '15 18:01

Anthony


People also ask

What is the use of Rakefile?

Rake is a tool you can use with Ruby projects. It allows you to use ruby code to define "tasks" that can be run in the command line. Rake can be downloaded and included in ruby projects as a ruby gem. Once installed, you define tasks in a file named "Rakefile" that you add to your project.

What does GitLab Rake do?

GitLab provides Rake tasks to assist you with common administration and operational processes. You can perform GitLab Rake tasks by using: gitlab-rake <raketask> for Omnibus GitLab installations.

What is a Rakefile?

Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax. Rake has the following features: Rakefiles (rake's version of Makefiles) are completely defined in standard Ruby syntax. No XML files to edit.


1 Answers

The line puts "I'm in setup" isn’t part of any task – it will be executed whatever task you specify, even a non-existent one, as the file is being parsed (strictly speaking not when Ruby is parsing the file, but as it is being executed and setting up the rake tasks):

$ rake foo
I'm in setup
rake aborted!
Don't know how to build task 'foo'

(See full trace by running task with --trace)

Only after the file has been read does the task lookup take place, and that is what that quote is referring to.

If you want some common code for all the tasks of a namespace you will need to create a task for it and make all other tasks in the namespace depend on it, e.g.:

namespace :setup do
  task :create => :default do
    puts "I'm in create"
  end

  task :default do
    puts "I'm in setup"
  end
end
like image 59
matt Avatar answered Sep 20 '22 11:09

matt