Jay Blanchard
Jay Blanchard

Reputation: 34416

Rake runs function twice

I started creating a set of Rake tasks (my first time, with limited Ruby experience) and when I run the first task, using either rake test or rake db, from the command line I get two outputs even though there is only one file in the directory in question.

rakefile.rb

require 'fileutils'

FILES    = ["html", "css", "js", "svg", "otf", "eot", "ttf", "woff", "jpeg", "map", "ico", "map", "png", "db"]

desc 'test script'
task :test => [:db]

task :db do
    copy_to 'data/', 'c:/xampp/htdocs/home/shared/data'
end

def copy_to(dest, src)

    files = FileList.new()
    files.include Dir.glob("#{src}/*.*")
    FILES.each {|ext| files.include "#{src}/*.#{ext}"}
    files.each do |src|
        puts "copying: #{src} to #{dest}"
        FileUtils.cp src, dest
    end

end

Output

(in C:/xampp/htdocs/home/gateway)                        
copying: c:/xampp/htdocs/home/shared/data/foo.db to data/   
copying: c:/xampp/htdocs/home/shared/data/foo.db to data/   

When I do rake -T I get the following (which is what I would expect):

(in C:/xampp/htdocs/home/gateway)
rake test  # test script

Of course foo.db only gets copied once, or the second copy overwrites the first one.

EDIT ran rake test --trace from the command line

** Invoke test (first_time)                                                   
** Invoke db (first_time)                                                     
** Execute db                                                                 
copying: c:/xampp/htdocs/home/shared/data/foo.db to data/ 
copying: c:/xampp/htdocs/home/shared/data/foo.db to data/ 
** Execute test                                                               

Is it executing :db and then :test? Or is :db running twice as it appears to be doing here? What am I missing? Have I done something wrong?

Upvotes: 1

Views: 218

Answers (1)

Jordan Running
Jordan Running

Reputation: 106037

The problem is that you're adding foo.db to the files FileList twice:

files.include Dir.glob("#{src}/*.*")
FILES.each {|ext| files.include "#{src}/*.#{ext}"}

Because FILES (which is a misleading variable name) includes "db", on the first line you're adding *.* to files and on the second line you're adding *.db to files.

It's not clear why you have both lines, since the first line will add every file in the directory, so the second line is only going to add files that you've already added.

Upvotes: 4

Related Questions