Pregunta

In a build.rake file I have an array holding names of JavaScript files:

JS_FROM_INDEX=`./bin/extract_files -e js index.html`.split

It holds these files:

js/config.js
js/vendor/dollar.js
js/vendor/ejs.min.js
js/utils.js
......
js/Viewport.js

Then there is a rule which (it is my guess as I'm completely ignorant to ruby yet) tells how to make the build/app.js file: namely take the js/config.js file first and then append all other files from the above array to it:

file DEST + '/app.js' => [DEST]+JS_FROM_INDEX.dup << 'index.html' << DEST do |t|
  sh "cat js/config.js > #{t.name}"
  sh "cat #{JS_FROM_INDEX.reject{|f| f =~ /\/config\.js/ }.join(" ")} | bin/yuicompressor --type js >> #{t.name}"
end

It works ok, but now I've found out, that js/utils.js should be at the very beginning, even before the js/config.js.

So my questions is:

Is there a nice way to sort the JS_FROM_INDEX array, so that js/utils.js and js/config.js are moved to its first positions? Can this be done as a oneliner (i.e. some code appended to the .split call above)?

UPDATE:

Meager has suggested (thank you!) the code:

scripts.unshift("js/config.js") if scripts.delete("js/config.js");
scripts.unshift("js/utils.js") if scripts.delete("js/utils.js");

To integrate that into the Rakefile I think I need to introduce 2 more variables:

JS_FROM_INDEX=`./bin/extract_files -e js index.html`.split
JS_SORTED_1=......use JS_FROM_INDEX somehow....
JS_SORTED_2=......use JS_FROM_SORTED_1 somehow....

file DEST + '/app.js' => [DEST]+JS_SORTED_2.dup << 'index.html' << DEST do |t|
  sh "cat #{JS_FROM_INDEX.reject{|f| f =~ /\/config\.js/ }.join(" ")} | bin/yuicompressor --type js >> #{t.name}"
end

Any ideas please on how to connect the dots above?

¿Fue útil?

Solución

Delete the item from the array and then (if it was found during the delete) push it onto the front of the array:

scripts = %w(js/config.js
            js/vendor/dollar.js
            js/vendor/ejs.min.js
            js/utils.js)

# Move config.js first
scripts.unshift("js/config.js") if scripts.delete("js/config.js");

# Move utils.js second to ensure it is always before config.js
scripts.unshift("js/utils.js") if scripts.delete("js/utils.js");

Here, delete returns nil if the item to delete wasn't found, so the item is never unshifted back onto the front.

You could easily make this more generic with by iterating over a list:

items_to_sort_to_front.each { |item| scripts.unshift(item) if scripts.delete(item) }

Just remember to sort items_to_sort_to_front backwards, as the last item in the list will be the last one moved to the front of scripts.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top