Search code examples
javascriptrubyguard

Using guard to minify javascript files into a different directory


I am trying to create my first guardfile and have run into difficulties trying to minify some of my javascript files.

I want guard to watch the 'app/assets/js' directory and any time a file is changed within this directory, for a minified version of the file to be created within 'public/js' with the same name and if possible within the same directory name.

For example were I to save the bootstrap.js file within app/assets/js/vendor I would like for the minified version to be placed within the public/js/vendor/bootstrap.min.js file.

Below are the relevant parts of my current guardfile:

require 'cssmin'
require 'jsmin'

module ::Guard
  class Refresher < Guard
  end
end

# 
guard :refresher do
  watch('public/css/styles.min.css') do |m|
    css = File.read(m[0])
    File.open(m[0], 'w') { |file| file.write(CSSMin.minify(css)) }
  end
  watch(%r[app/assets/js/.+]) do |m|
    js = File.read(m[0])
    File.open(m[0], 'w') { |file| file.write(JSMin.minify(js)) }
  end
end

This is my first experience of Ruby and so beginner orientated answers would be appreciated. Thanks.


Solution

  • You write to the same file you're reading. According to your question, you need something like:

    watch(%r[app/assets/js/(.+)]) do |m|
      File.write("public/js/#{ m[1] }", JSMin.minify(File.read(m[0])))
    end
    

    Please note the capture group I've added to the regexp, so I can grab the filename with m[1].