William Entriken
William Entriken

Reputation: 39243

Rakefiles: variable scope available in `load`ed scripts

In my ~/Sites/ directory I have the omnipotent Rakefile:

desc "Run deliver in each directory"
task :deliver do
  sh 'for a in $(ls ./*/Rakefile); do (cd $(dirname $a); rake -f Rakefile deliver); done'
end

(Along with other fun production tasks, and the stupid "default" task that lists all tasks [see https://github.com/ruby/rake/issues/22])

Some directories inside Sites have a Rakefile in them. Most look like this:

# Rsync options
production_server = 'pacificmedicaltraining.net'
production_user = 'training2'
production_www_dir = 'www'
local_www_dir = 'www'
local_git_dir = 'git'

desc "Run all build and deployment tasks, for continuous delivery"
task :deliver => [:pullgit, :buildjekyll, :pushproduction]

desc "Bring deployed server files local"
task :pullgit do
  puts 'Pulling git'
  sh "cd '#{local_git_dir}'; git pull"
  puts 'Pulled'
end

...

The behavior of this Rakefile is defined fully by the options at the top and the deliver task (other sites might not use Jekyll for building). All remaining tasks in this file are copy-paste. In the interest of DRY, I have removed the copy-pasted tasks into ~/Sites/common.rake and included this file with load '../common.rake' in the contributing files.

Pulling git rake aborted! NameError: undefined local variable or method 'local_git_dir' for main:Object /Users/williamentriken/Sites/common.rake:4:in 'block in ' Tasks: TOP => pullgit (See full trace by running task with --trace)

How do I make that variable available to the loaded script?

Upvotes: 0

Views: 55

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369420

How do I make that variable available to the loaded script?

You can't. It's a local variable. Local variables are local to the scope they are defined in, they don't exist in other scopes. That's why they are called local variables.

Upvotes: -1

Related Questions