Last active
February 21, 2016 05:21
-
-
Save kazu69/9570672 to your computer and use it in GitHub Desktop.
Custom assets compile with Sprockets and YUI Compressor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'https://rubygems.org' | |
group :development do | |
gem 'rake' | |
gem 'sprockets' | |
gem 'yui-compressor' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :assets_compile do | |
require 'rubygems' | |
require 'bundler' | |
Bundler.require | |
desc 'compression and combined js' | |
task :javascripts do | |
root = File.dirname(__FILE__) | |
assets_path = File.join root, 'assets' | |
js_assets_path = File.join assets_path, 'javascripts' # Sprocketsのload pathに追加する | |
outpath = File.join('public', 'javascripts') | |
outfile = Pathname.new(outpath).join('application.js') | |
# ディレクトリとファイル作成 | |
FileUtils.mkdir_p outfile.dirname | |
File.open(outfile,'w'){|file| file = nil} | |
# Compression | |
sprockets = Sprockets::Environment.new | |
sprockets.js_compressor = YUI::JavaScriptCompressor.new munge: true | |
files = [ | |
'jquery/jquery.min.js', | |
'underscorejs/underscore.js', | |
'lodash/lodash.min.js', | |
'custom/common.js', | |
'custom/app.js' | |
] | |
sprockets.append_path(js_assets_path).to_s | |
files.each do |file| | |
asset = sprockets.find_asset file # assetはSprockets::BundleAssetとなる | |
# このインスタンスをto_sするとファイルの中身が得られる | |
# javascriptファイル内のコメントを削除する | |
asset.to_s.gsub! /\/\*!.*?\*\//m, '' | |
File.open(outfile, 'a+') do |f| | |
file_name = File::basename(file).to_s | |
comments = <<-EOS | |
/** | |
* #{file_name} | |
* @date #{asset.mtime} | |
*/ | |
EOS | |
end | |
# sleep しないとコメントが挿入できないときがある | |
sleep 1.0/10.0 | |
f.puts comments | |
f.puts asset | |
end | |
end | |
puts "successfully compile application.js" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment