forked from sendgrid/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminify_js.rb
More file actions
87 lines (72 loc) · 2.6 KB
/
Copy pathminify_js.rb
File metadata and controls
87 lines (72 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
module Jekyll
$minified_filename = ''
# use this as a workaround for getting cleaned up
# reference: https://gist.github.com/920651
class JsMinifyFile < StaticFile
def write(dest)
# do nothing
end
end
# minify js files
class JsMinifyGenerator < Generator
safe true
def generate(site)
config = Jekyll::JsMinifyGenerator.get_config
files_to_minify = config['files'] || get_js_files(site, config['js_source'])
last_modified = files_to_minify.reduce( Time.at(0) ) do |latest,filepath|
modified = File.mtime(filepath)
modified > latest ? modified : latest
end
# reset the minified filename
$minified_filename = last_modified.strftime("%Y%m%d%H%M") + '.min.js'
output_dir = File.join(site.config['destination'], config['js_destination'])
output_file = File.join(output_dir, $minified_filename)
# need to create destination dir if it doesn't exist
FileUtils.mkdir_p(output_dir)
minify_js(files_to_minify, output_file, site.source)
site.static_files << JsMinifyFile.new(site, site.source, config['js_destination'], $minified_filename)
end
# read the js dir for the js files to compile
def get_js_files(site, relative_dir)
# not sure if we need to do this, but keep track of the current dir
pwd = Dir.pwd
Dir.chdir(File.join(site.config['source'], relative_dir))
# read js files
js_files = Dir.glob('*.js').map{ |f| File.join(relative_dir, f) }
Dir.chdir(pwd)
return js_files
end
def minify_js(js_files, output_file, source)
js_files = js_files.join(' ')
juice_cmd = "juicer merge -s -f #{js_files} -o #{output_file} -d #{source}"
puts juice_cmd
if system(juice_cmd) == false
raise 'Juicer failed while minifying javascript.'
end
end
# Load configuration from JsMinify.yml
def self.get_config
if @config == nil
@config = {
'js_source' => 'javascripts', # relative to the route
'js_destination' => '/javascripts' # relative to site.config['destination']
}
config = YAML.load_file('JsMinify.yml') rescue nil
if config.is_a?(Hash)
@config = @config.merge(config)
end
end
return @config
end
end
class JsMinifyLinkTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
end
def render(context)
config = Jekyll::JsMinifyGenerator.get_config
File.join(config['js_destination'], $minified_filename)
end
end
end
Liquid::Template.register_tag('minified_js_file', Jekyll::JsMinifyLinkTag)