Rakefile multitask- How to for loop and create task and execute them

768 views Asked by At

I have the following folder structure that i need to run compass watch on:

|   config.rb
|   rakefile.rb
+---folder1
|   +---css 
|   +---img
|   +---js
|   \---sass
|           
+---folder2
|   +---css 
|   +---img
|   +---js  
|   \---sass
|           
\---folder3
    +---css
    +---img
    +---js
    \---sass

I keep the config.rb outside because it all contains the same js, img, css folders config with the same :output settings.

Here's my rakefile.rb to watch for all folders:

desc 'Compile folder1 sass'
task :watch_1 do
puts 'Watching folder1 sass...'
system 'compass watch --sass-dir folder1/sass --css-dir folder1/css -c config.rb'
end

desc 'Compile folder2 sass'
task :watch_2 do
puts 'Watching folder2 sass...'
system 'compass watch --sass-dir folder2/sass --css-dir folder2/css -c config.rb'
end

desc 'Compile folder3 sass'
task :watch_3 do
puts 'Watching folder3 sass...'
system 'compass watch --sass-dir folder3/sass --css-dir folder3/css -c config.rb'
end

# Watch all sass folder to compile css.
multitask :watch_all => [:watch_1, :watch_2, :watch_3] do
puts 'Watching all...'
end

My question is... How can i for loop and run the task in the rakefile.rb when i have new folder? I read around but i am stuck at creating the task. Here's my pseudo codes:

$folders = ['folder1', 'folder2', ... , 'folderN'];
foreach $folder in $folders do
    system 'compass watch --sass-dir $folder/sass --css-dir $folder/css -c config.rb'
end
2

There are 2 answers

2
iSvetlanko On

You can do it in ruby-way..by using "each" loop. For example:

folders = ['folder1', 'folder2', ... , 'folderN']
folders.each do |folder|
  system 'compass watch --sass-dir folder/sass --css-dir folder/css -c config.rb'
end

Or using a block:

folders = ['folder1', 'folder2', ... , 'folderN']
folders.each { |folder| system 'compass watch --sass-dir folder/sass --css-dir folder/css -c config.rb' }

Is it the answer you were looking for?

0
zen.c On

So far what i have is this. And its working fine so far. But some strange behaviors in that when i made changes to folder 1 scss, the terminal windows reports "identical folder1/css/main.css" although investigating the file folder1/css/main.css the changes have been compiled correctly. Other than that, here the rakefile.rb codes that worked for me:

threads = []
folders = ['folder1', 'folder2', 'folder3']

for folder in folders
    threads << Thread.new(folder) { |thefolder|
        puts "Watching #{thefolder}/sass"
        system "compass watch --sass-dir #{thefolder}/sass --css-dir #{thefolder}/css -c config.rb"
    }
end

threads.each { |thethread| thethread.join }