moxiesoft-jammit 0.5.4
Sign up to get free protection for your applications and to get access to all the features.
- data/LICENSE +22 -0
- data/README +24 -0
- data/bin/jammit +5 -0
- data/jammit.gemspec +34 -0
- data/lib/jammit.rb +199 -0
- data/lib/jammit/command_line.rb +77 -0
- data/lib/jammit/compressor.rb +251 -0
- data/lib/jammit/controller.rb +94 -0
- data/lib/jammit/dependencies.rb +28 -0
- data/lib/jammit/helper.rb +81 -0
- data/lib/jammit/jst.js +1 -0
- data/lib/jammit/packager.rb +162 -0
- data/lib/jammit/railtie.rb +14 -0
- data/lib/jammit/routes.rb +23 -0
- data/rails/routes.rb +10 -0
- metadata +95 -0
data/LICENSE
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
Copyright (c) 2009 Jeremy Ashkenas, DocumentCloud
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person
|
4
|
+
obtaining a copy of this software and associated documentation
|
5
|
+
files (the "Software"), to deal in the Software without
|
6
|
+
restriction, including without limitation the rights to use,
|
7
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
8
|
+
copies of the Software, and to permit persons to whom the
|
9
|
+
Software is furnished to do so, subject to the following
|
10
|
+
conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be
|
13
|
+
included in all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
17
|
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
18
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
19
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
20
|
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
data/README
ADDED
@@ -0,0 +1,24 @@
|
|
1
|
+
==
|
2
|
+
_ _ __ __ __ __ ___ _____
|
3
|
+
_ | |/_\ | \/ | \/ |_ _|_ _|
|
4
|
+
| || / _ \| |\/| | |\/| || | | |
|
5
|
+
\__/_/ \_\_| |_|_| |_|___| |_|
|
6
|
+
|
7
|
+
|
8
|
+
Jammit is an industrial strength asset packaging library for Rails,
|
9
|
+
providing both the CSS and JavaScript concatenation and compression
|
10
|
+
that you'd expect, as well as ahead-of-time gzipping, built-in JavaScript
|
11
|
+
template support, and optional Data-URI / MHTML image embedding.
|
12
|
+
|
13
|
+
Installation:
|
14
|
+
gem install jammit
|
15
|
+
|
16
|
+
For documentation, usage, and examples, see:
|
17
|
+
http://documentcloud.github.com/jammit/
|
18
|
+
|
19
|
+
To suggest a feature or report a bug:
|
20
|
+
http://github.com/documentcloud/jammit/issues/
|
21
|
+
|
22
|
+
For internal source docs, see:
|
23
|
+
http://documentcloud.github.com/jammit/doc/
|
24
|
+
|
data/bin/jammit
ADDED
data/jammit.gemspec
ADDED
@@ -0,0 +1,34 @@
|
|
1
|
+
Gem::Specification.new do |s|
|
2
|
+
s.name = 'moxiesoft-jammit'
|
3
|
+
s.version = '0.5.4' # Keep version in sync with jammit.rb
|
4
|
+
s.date = '2010-08-11'
|
5
|
+
|
6
|
+
s.homepage = "http://documentcloud.github.com/jammit/"
|
7
|
+
s.summary = "Industrial Strength Asset Packaging for Rails"
|
8
|
+
s.description = <<-EOS
|
9
|
+
Jammit is an industrial strength asset packaging library for Rails,
|
10
|
+
providing both the CSS and JavaScript concatenation and compression that
|
11
|
+
you'd expect, as well as YUI Compressor and Closure Compiler compatibility,
|
12
|
+
ahead-of-time gzipping, built-in JavaScript template support, and optional
|
13
|
+
Data-URI / MHTML image embedding.
|
14
|
+
EOS
|
15
|
+
|
16
|
+
s.authors = ['Jeremy Ashkenas']
|
17
|
+
s.email = 'jeremy@documentcloud.org'
|
18
|
+
s.rubyforge_project = 'jammit'
|
19
|
+
|
20
|
+
s.require_paths = ['lib']
|
21
|
+
s.executables = ['jammit']
|
22
|
+
|
23
|
+
s.has_rdoc = true
|
24
|
+
s.extra_rdoc_files = ['README']
|
25
|
+
s.rdoc_options << '--title' << 'Jammit' <<
|
26
|
+
'--exclude' << 'test' <<
|
27
|
+
'--main' << 'README' <<
|
28
|
+
'--all'
|
29
|
+
|
30
|
+
s.add_dependency 'yui-compressor', ['>= 0.9.1']
|
31
|
+
s.add_dependency 'closure-compiler', ['>= 0.1.0']
|
32
|
+
|
33
|
+
s.files = Dir['lib/**/*', 'bin/*', 'rails/*', 'jammit.gemspec', 'LICENSE', 'README']
|
34
|
+
end
|
data/lib/jammit.rb
ADDED
@@ -0,0 +1,199 @@
|
|
1
|
+
$LOAD_PATH.push File.expand_path(File.dirname(__FILE__))
|
2
|
+
|
3
|
+
# @Jammit@ is the central namespace for all Jammit classes, and provides access
|
4
|
+
# to all of the configuration options.
|
5
|
+
module Jammit
|
6
|
+
|
7
|
+
VERSION = "0.5.4"
|
8
|
+
|
9
|
+
ROOT = File.expand_path(File.dirname(__FILE__) + '/..')
|
10
|
+
|
11
|
+
ASSET_ROOT = File.expand_path((defined?(Rails) && Rails.root.to_s.length > 0) ? Rails.root : ".") unless defined?(ASSET_ROOT)
|
12
|
+
|
13
|
+
PUBLIC_ROOT = (defined?(Rails) && Rails.public_path.to_s.length > 0) ? Rails.public_path : File.join(ASSET_ROOT, 'public') unless defined?(PUBLIC_ROOT)
|
14
|
+
|
15
|
+
DEFAULT_CONFIG_PATH = File.join(ASSET_ROOT, 'config', 'assets.yml')
|
16
|
+
|
17
|
+
DEFAULT_PACKAGE_PATH = "assets"
|
18
|
+
|
19
|
+
DEFAULT_JST_SCRIPT = File.join(ROOT, 'lib/jammit/jst.js')
|
20
|
+
|
21
|
+
DEFAULT_JST_COMPILER = "template"
|
22
|
+
|
23
|
+
DEFAULT_JST_NAMESPACE = "window.JST"
|
24
|
+
|
25
|
+
AVAILABLE_COMPRESSORS = [:yui, :closure]
|
26
|
+
|
27
|
+
DEFAULT_COMPRESSOR = :yui
|
28
|
+
|
29
|
+
# Extension matchers for JavaScript and JST, which need to be disambiguated.
|
30
|
+
JS_EXTENSION = /\.js\Z/
|
31
|
+
DEFAULT_JST_EXTENSION = "jst"
|
32
|
+
|
33
|
+
# Jammit raises a @PackageNotFound@ exception when a non-existent package is
|
34
|
+
# requested by a browser -- rendering a 404.
|
35
|
+
class PackageNotFound < NameError; end
|
36
|
+
|
37
|
+
# Jammit raises a ConfigurationNotFound exception when you try to load the
|
38
|
+
# configuration of an assets.yml file that doesn't exist.
|
39
|
+
class ConfigurationNotFound < NameError; end
|
40
|
+
|
41
|
+
# Jammit raises an OutputNotWritable exception if the output directory for
|
42
|
+
# cached packages is locked.
|
43
|
+
class OutputNotWritable < StandardError; end
|
44
|
+
|
45
|
+
# Jammit raises a DeprecationError if you try to use an outdated feature.
|
46
|
+
class DeprecationError < StandardError; end
|
47
|
+
|
48
|
+
class << self
|
49
|
+
attr_reader :configuration, :template_function, :template_namespace,
|
50
|
+
:embed_assets, :package_assets, :compress_assets, :gzip_assets,
|
51
|
+
:package_path, :mhtml_enabled, :include_jst_script, :config_path,
|
52
|
+
:javascript_compressor, :compressor_options, :css_compressor_options,
|
53
|
+
:template_extension, :template_extension_matcher
|
54
|
+
end
|
55
|
+
|
56
|
+
# The minimal required configuration.
|
57
|
+
@configuration = {}
|
58
|
+
@package_path = DEFAULT_PACKAGE_PATH
|
59
|
+
|
60
|
+
# Load the complete asset configuration from the specified @config_path@.
|
61
|
+
# If we're loading softly, don't let missing configuration error out.
|
62
|
+
def self.load_configuration(config_path, soft=false)
|
63
|
+
exists = config_path && File.exists?(config_path)
|
64
|
+
return false if soft && !exists
|
65
|
+
raise ConfigurationNotFound, "could not find the \"#{config_path}\" configuration file" unless exists
|
66
|
+
conf = YAML.load(ERB.new(File.read(config_path)).result)
|
67
|
+
@config_path = config_path
|
68
|
+
@configuration = symbolize_keys(conf)
|
69
|
+
@package_path = conf[:package_path] || DEFAULT_PACKAGE_PATH
|
70
|
+
@embed_assets = conf[:embed_assets] || conf[:embed_images]
|
71
|
+
@compress_assets = !(conf[:compress_assets] == false)
|
72
|
+
@gzip_assets = !(conf[:gzip_assets] == false)
|
73
|
+
@mhtml_enabled = @embed_assets && @embed_assets != "datauri"
|
74
|
+
@compressor_options = symbolize_keys(conf[:compressor_options] || {})
|
75
|
+
@css_compressor_options = symbolize_keys(conf[:css_compressor_options] || {})
|
76
|
+
set_javascript_compressor(conf[:javascript_compressor])
|
77
|
+
set_package_assets(conf[:package_assets])
|
78
|
+
set_template_function(conf[:template_function])
|
79
|
+
set_template_namespace(conf[:template_namespace])
|
80
|
+
set_template_extension(conf[:template_extension])
|
81
|
+
symbolize_keys(conf[:stylesheets]) if conf[:stylesheets]
|
82
|
+
symbolize_keys(conf[:javascripts]) if conf[:javascripts]
|
83
|
+
check_java_version
|
84
|
+
check_for_deprecations
|
85
|
+
self
|
86
|
+
end
|
87
|
+
|
88
|
+
# Force a reload by resetting the Packager and reloading the configuration.
|
89
|
+
# In development, this will be called as a before_filter before every request.
|
90
|
+
def self.reload!
|
91
|
+
Thread.current[:jammit_packager] = nil
|
92
|
+
load_configuration(@config_path)
|
93
|
+
end
|
94
|
+
|
95
|
+
# Keep a global (thread-local) reference to a @Jammit::Packager@, to avoid
|
96
|
+
# recomputing asset lists unnecessarily.
|
97
|
+
def self.packager
|
98
|
+
Thread.current[:jammit_packager] ||= Packager.new
|
99
|
+
end
|
100
|
+
|
101
|
+
# Generate the base filename for a version of a given package.
|
102
|
+
def self.filename(package, extension, suffix=nil)
|
103
|
+
suffix_part = suffix ? "-#{suffix}" : ''
|
104
|
+
"#{package}#{suffix_part}.#{extension}"
|
105
|
+
end
|
106
|
+
|
107
|
+
# Generates the server-absolute URL to an asset package.
|
108
|
+
def self.asset_url(package, extension, suffix=nil, mtime=nil)
|
109
|
+
timestamp = mtime ? "?#{mtime.to_i}" : ''
|
110
|
+
"/#{package_path}/#{filename(package, extension, suffix)}#{timestamp}"
|
111
|
+
end
|
112
|
+
|
113
|
+
# Convenience method for packaging up Jammit, using the default options.
|
114
|
+
def self.package!(options={})
|
115
|
+
options = {
|
116
|
+
:config_path => Jammit::DEFAULT_CONFIG_PATH,
|
117
|
+
:output_folder => nil,
|
118
|
+
:base_url => nil,
|
119
|
+
:force => false
|
120
|
+
}.merge(options)
|
121
|
+
load_configuration(options[:config_path])
|
122
|
+
packager.force = options[:force]
|
123
|
+
packager.precache_all(options[:output_folder], options[:base_url])
|
124
|
+
end
|
125
|
+
|
126
|
+
private
|
127
|
+
|
128
|
+
# Ensure that the JavaScript compressor is a valid choice.
|
129
|
+
def self.set_javascript_compressor(value)
|
130
|
+
value = value && value.to_sym
|
131
|
+
@javascript_compressor = AVAILABLE_COMPRESSORS.include?(value) ? value : DEFAULT_COMPRESSOR
|
132
|
+
end
|
133
|
+
|
134
|
+
# Turn asset packaging on or off, depending on configuration and environment.
|
135
|
+
def self.set_package_assets(value)
|
136
|
+
package_env = !defined?(Rails) || (!Rails.env.development? && !Rails.env.test?)
|
137
|
+
@package_assets = value == true || value.nil? ? package_env :
|
138
|
+
value == 'always' ? true : false
|
139
|
+
end
|
140
|
+
|
141
|
+
# Assign the JST template function, unless explicitly turned off.
|
142
|
+
def self.set_template_function(value)
|
143
|
+
@template_function = value == true || value.nil? ? DEFAULT_JST_COMPILER :
|
144
|
+
value == false ? '' : value
|
145
|
+
@include_jst_script = @template_function == DEFAULT_JST_COMPILER
|
146
|
+
end
|
147
|
+
|
148
|
+
# Set the root JS object in which to stash all compiled JST.
|
149
|
+
def self.set_template_namespace(value)
|
150
|
+
@template_namespace = value == true || value.nil? ? DEFAULT_JST_NAMESPACE : value.to_s
|
151
|
+
end
|
152
|
+
|
153
|
+
# Set the extension for JS templates.
|
154
|
+
def self.set_template_extension(value)
|
155
|
+
@template_extension = (value == true || value.nil? ? DEFAULT_JST_EXTENSION : value.to_s).gsub(/\A\.?(.*)\Z/, '\1')
|
156
|
+
@template_extension_matcher = /\.#{Regexp.escape(@template_extension)}\Z/
|
157
|
+
end
|
158
|
+
|
159
|
+
# The YUI Compressor requires Java > 1.4, and Closure requires Java > 1.6.
|
160
|
+
def self.check_java_version
|
161
|
+
return true if @checked_java_version
|
162
|
+
java = @compressor_options[:java] || 'java'
|
163
|
+
@css_compressor_options[:java] ||= java if @compressor_options[:java]
|
164
|
+
version = (`#{java} -version 2>&1`)[/\d+\.\d+/]
|
165
|
+
disable_compression if !version ||
|
166
|
+
(@javascript_compressor == :closure && version < '1.6') ||
|
167
|
+
(@javascript_compressor == :yui && version < '1.4')
|
168
|
+
@checked_java_version = true
|
169
|
+
end
|
170
|
+
|
171
|
+
# If we don't have a working Java VM, then disable asset compression and
|
172
|
+
# complain loudly.
|
173
|
+
def self.disable_compression
|
174
|
+
@compress_assets = false
|
175
|
+
warn("Asset compression disabled -- Java unavailable.")
|
176
|
+
end
|
177
|
+
|
178
|
+
# Jammit 0.5+ no longer supports separate template packages.
|
179
|
+
def self.check_for_deprecations
|
180
|
+
raise DeprecationError, "Jammit 0.5+ no longer supports separate packages for templates.\nPlease fold your templates into the appropriate 'javascripts' package instead." if @configuration[:templates]
|
181
|
+
end
|
182
|
+
|
183
|
+
def self.warn(message)
|
184
|
+
message = "Jammit Warning: #{message}"
|
185
|
+
$stderr.puts message
|
186
|
+
end
|
187
|
+
|
188
|
+
# Clone of active_support's symbolize_keys, so that we don't have to depend
|
189
|
+
# on active_support in any fashion. Converts a hash's keys to all symbols.
|
190
|
+
def self.symbolize_keys(hash)
|
191
|
+
hash.keys.each do |key|
|
192
|
+
hash[(key.to_sym rescue key) || key] = hash.delete(key)
|
193
|
+
end
|
194
|
+
hash
|
195
|
+
end
|
196
|
+
|
197
|
+
end
|
198
|
+
|
199
|
+
require 'jammit/dependencies'
|
@@ -0,0 +1,77 @@
|
|
1
|
+
require 'optparse'
|
2
|
+
require File.expand_path(File.dirname(__FILE__) + '/../jammit')
|
3
|
+
|
4
|
+
module Jammit
|
5
|
+
|
6
|
+
# The @CommandLine@ is able to compress, pre-package, and pre-gzip all the
|
7
|
+
# assets specified in the configuration file, in order to avoid an initial
|
8
|
+
# round of slow requests after a fresh deployment.
|
9
|
+
class CommandLine
|
10
|
+
|
11
|
+
BANNER = <<-EOS
|
12
|
+
|
13
|
+
Usage: jammit OPTIONS
|
14
|
+
|
15
|
+
Run jammit inside a Rails application to compresses all JS, CSS,
|
16
|
+
and JST according to config/assets.yml, saving the packaged
|
17
|
+
files and corresponding gzipped versions.
|
18
|
+
|
19
|
+
If you're using "embed_assets", and you wish to precompile the
|
20
|
+
MHTML stylesheet variants, you must specify the "base-url".
|
21
|
+
|
22
|
+
Options:
|
23
|
+
EOS
|
24
|
+
|
25
|
+
# The @Jammit::CommandLine@ runs from the contents of @ARGV@.
|
26
|
+
def initialize
|
27
|
+
parse_options
|
28
|
+
ensure_configuration_file
|
29
|
+
Jammit.package!(@options)
|
30
|
+
end
|
31
|
+
|
32
|
+
|
33
|
+
private
|
34
|
+
|
35
|
+
# Make sure that we have a readable configuration file. The @jammit@
|
36
|
+
# command can't run without one.
|
37
|
+
def ensure_configuration_file
|
38
|
+
config = @options[:config_path]
|
39
|
+
return true if File.exists?(config) && File.readable?(config)
|
40
|
+
puts "Could not find the asset configuration file \"#{config}\""
|
41
|
+
exit(1)
|
42
|
+
end
|
43
|
+
|
44
|
+
# Uses @OptionParser@ to grab the options: *--output*, *--config*, and
|
45
|
+
# *--base-url*...
|
46
|
+
def parse_options
|
47
|
+
@options = {
|
48
|
+
:config_path => Jammit::DEFAULT_CONFIG_PATH,
|
49
|
+
:output_folder => nil,
|
50
|
+
:base_url => nil,
|
51
|
+
:force => false
|
52
|
+
}
|
53
|
+
@option_parser = OptionParser.new do |opts|
|
54
|
+
opts.on('-o', '--output PATH', 'output folder for packages (default: "public/assets")') do |output_folder|
|
55
|
+
@options[:output_folder] = output_folder
|
56
|
+
end
|
57
|
+
opts.on('-c', '--config PATH', 'path to assets.yml (default: "config/assets.yml")') do |config_path|
|
58
|
+
@options[:config_path] = config_path
|
59
|
+
end
|
60
|
+
opts.on('-u', '--base-url URL', 'base URL for MHTML (ex: "http://example.com")') do |base_url|
|
61
|
+
@options[:base_url] = base_url
|
62
|
+
end
|
63
|
+
opts.on('-f', '--force', 'force a rebuild of all assets') do |force|
|
64
|
+
@options[:force] = force
|
65
|
+
end
|
66
|
+
opts.on_tail('-v', '--version', 'display Jammit version') do
|
67
|
+
puts "Jammit version #{Jammit::VERSION}"
|
68
|
+
exit
|
69
|
+
end
|
70
|
+
end
|
71
|
+
@option_parser.banner = BANNER
|
72
|
+
@option_parser.parse!(ARGV)
|
73
|
+
end
|
74
|
+
|
75
|
+
end
|
76
|
+
|
77
|
+
end
|
@@ -0,0 +1,251 @@
|
|
1
|
+
module Jammit
|
2
|
+
|
3
|
+
# Uses the YUI Compressor or Closure Compiler to compress JavaScript.
|
4
|
+
# Always uses YUI to compress CSS (Which means that Java must be installed.)
|
5
|
+
# Also knows how to create a concatenated JST file.
|
6
|
+
# If "embed_assets" is turned on, creates "mhtml" and "datauri" versions of
|
7
|
+
# all stylesheets, with all enabled assets inlined into the css.
|
8
|
+
class Compressor
|
9
|
+
|
10
|
+
# Mapping from extension to mime-type of all embeddable assets.
|
11
|
+
EMBED_MIME_TYPES = {
|
12
|
+
'.png' => 'image/png',
|
13
|
+
'.jpg' => 'image/jpeg',
|
14
|
+
'.jpeg' => 'image/jpeg',
|
15
|
+
'.gif' => 'image/gif',
|
16
|
+
'.tif' => 'image/tiff',
|
17
|
+
'.tiff' => 'image/tiff',
|
18
|
+
'.ttf' => 'font/truetype',
|
19
|
+
'.otf' => 'font/opentype',
|
20
|
+
'.woff' => 'font/woff'
|
21
|
+
}
|
22
|
+
|
23
|
+
# Font extensions for which we allow embedding:
|
24
|
+
EMBED_EXTS = EMBED_MIME_TYPES.keys
|
25
|
+
EMBED_FONTS = ['.ttf', '.otf', '.woff']
|
26
|
+
|
27
|
+
# (32k - padding) maximum length for data-uri assets (an IE8 limitation).
|
28
|
+
MAX_IMAGE_SIZE = 32700
|
29
|
+
|
30
|
+
# CSS asset-embedding regexes for URL rewriting.
|
31
|
+
EMBED_DETECTOR = /url\(['"]?([^\s)]+\.[a-z]+)(\?\d+)?['"]?\)/
|
32
|
+
EMBEDDABLE = /[\A\/]embed\//
|
33
|
+
EMBED_REPLACER = /url\(__EMBED__(.+?)(\?\d+)?\)/
|
34
|
+
|
35
|
+
# MHTML file constants.
|
36
|
+
MHTML_START = "/*\r\nContent-Type: multipart/related; boundary=\"MHTML_MARK\"\r\n\r\n"
|
37
|
+
MHTML_SEPARATOR = "--MHTML_MARK\r\n"
|
38
|
+
MHTML_END = "\r\n--MHTML_MARK--\r\n*/\r\n"
|
39
|
+
|
40
|
+
# JST file constants.
|
41
|
+
JST_START = "(function(){"
|
42
|
+
JST_END = "})();"
|
43
|
+
|
44
|
+
COMPRESSORS = {
|
45
|
+
:yui => YUI::JavaScriptCompressor,
|
46
|
+
:closure => Closure::Compiler
|
47
|
+
}
|
48
|
+
|
49
|
+
DEFAULT_OPTIONS = {
|
50
|
+
:yui => {:munge => true},
|
51
|
+
:closure => {}
|
52
|
+
}
|
53
|
+
|
54
|
+
# Creating a compressor initializes the internal YUI Compressor from
|
55
|
+
# the "yui-compressor" gem, or the internal Closure Compiler from the
|
56
|
+
# "closure-compiler" gem.
|
57
|
+
def initialize
|
58
|
+
@css_compressor = YUI::CssCompressor.new(Jammit.css_compressor_options || {})
|
59
|
+
flavor = Jammit.javascript_compressor || Jammit::DEFAULT_COMPRESSOR
|
60
|
+
@options = DEFAULT_OPTIONS[flavor].merge(Jammit.compressor_options || {})
|
61
|
+
@js_compressor = COMPRESSORS[flavor].new(@options)
|
62
|
+
end
|
63
|
+
|
64
|
+
# Concatenate together a list of JavaScript paths, and pass them through the
|
65
|
+
# YUI Compressor (with munging enabled). JST can optionally be included.
|
66
|
+
def compress_js(paths)
|
67
|
+
if (jst_paths = paths.grep(Jammit.template_extension_matcher)).empty?
|
68
|
+
js = concatenate(paths)
|
69
|
+
else
|
70
|
+
js = concatenate(paths - jst_paths) + compile_jst(jst_paths)
|
71
|
+
end
|
72
|
+
Jammit.compress_assets ? @js_compressor.compress(js) : js
|
73
|
+
end
|
74
|
+
|
75
|
+
# Concatenate and compress a list of CSS stylesheets. When compressing a
|
76
|
+
# :datauri or :mhtml variant, post-processes the result to embed
|
77
|
+
# referenced assets.
|
78
|
+
def compress_css(paths, variant=nil, asset_url=nil)
|
79
|
+
@asset_contents = {}
|
80
|
+
css = concatenate_and_tag_assets(paths, variant)
|
81
|
+
css = @css_compressor.compress(css) if Jammit.compress_assets
|
82
|
+
case variant
|
83
|
+
when nil then return css
|
84
|
+
when :datauri then return with_data_uris(css)
|
85
|
+
when :mhtml then return with_mhtml(css, asset_url)
|
86
|
+
else raise PackageNotFound, "\"#{variant}\" is not a valid stylesheet variant"
|
87
|
+
end
|
88
|
+
end
|
89
|
+
|
90
|
+
# Compiles a single JST file by writing out a javascript that adds
|
91
|
+
# template properties to a top-level template namespace object. Adds a
|
92
|
+
# JST-compilation function to the top of the package, unless you've
|
93
|
+
# specified your own preferred function, or turned it off.
|
94
|
+
# JST templates are named with the basename of their file.
|
95
|
+
def compile_jst(paths)
|
96
|
+
namespace = Jammit.template_namespace
|
97
|
+
paths = paths.grep(Jammit.template_extension_matcher).sort
|
98
|
+
base_path = find_base_path(paths)
|
99
|
+
compiled = paths.map do |path|
|
100
|
+
contents = read_binary_file(path)
|
101
|
+
contents = contents.gsub(/\n/, '').gsub("'", '\\\\\'')
|
102
|
+
name = template_name(path, base_path)
|
103
|
+
"#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');"
|
104
|
+
end
|
105
|
+
compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : '';
|
106
|
+
setup_namespace = "#{namespace} = #{namespace} || {};"
|
107
|
+
[JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n")
|
108
|
+
end
|
109
|
+
|
110
|
+
|
111
|
+
private
|
112
|
+
|
113
|
+
# Given a set of paths, find a common prefix path.
|
114
|
+
def find_base_path(paths)
|
115
|
+
return nil if paths.length <= 1
|
116
|
+
paths.sort!
|
117
|
+
first = paths.first.split('/')
|
118
|
+
last = paths.last.split('/')
|
119
|
+
i = 0
|
120
|
+
while first[i] == last[i] && i <= first.length
|
121
|
+
i += 1
|
122
|
+
end
|
123
|
+
res = first.slice(0, i).join('/')
|
124
|
+
res.empty? ? nil : res
|
125
|
+
end
|
126
|
+
|
127
|
+
# Determine the name of a JS template. If there's a common base path, use
|
128
|
+
# the namespaced prefix. Otherwise, simply use the filename.
|
129
|
+
def template_name(path, base_path)
|
130
|
+
return File.basename(path, ".#{Jammit.template_extension}") unless base_path
|
131
|
+
path.gsub(/\A#{base_path}\/(.*)\.#{Jammit.template_extension}\Z/, '\1')
|
132
|
+
end
|
133
|
+
|
134
|
+
# In order to support embedded assets from relative paths, we need to
|
135
|
+
# expand the paths before contatenating the CSS together and losing the
|
136
|
+
# location of the original stylesheet path. Validate the assets while we're
|
137
|
+
# at it.
|
138
|
+
def concatenate_and_tag_assets(paths, variant=nil)
|
139
|
+
stylesheets = [paths].flatten.map do |css_path|
|
140
|
+
contents = read_binary_file(css_path)
|
141
|
+
contents.gsub(EMBED_DETECTOR) do |url|
|
142
|
+
ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path))
|
143
|
+
is_url = URI.parse($1).absolute?
|
144
|
+
is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})"
|
145
|
+
end
|
146
|
+
end
|
147
|
+
stylesheets.join("\n")
|
148
|
+
end
|
149
|
+
|
150
|
+
# Re-write all enabled asset URLs in a stylesheet with their corresponding
|
151
|
+
# Data-URI Base-64 encoded asset contents.
|
152
|
+
def with_data_uris(css)
|
153
|
+
css.force_encoding('UTF-8').gsub(EMBED_REPLACER) do |url|
|
154
|
+
"url(\"data:#{mime_type($1)};charset=utf-8;base64,#{encoded_contents($1)}\")"
|
155
|
+
end
|
156
|
+
end
|
157
|
+
|
158
|
+
# Re-write all enabled asset URLs in a stylesheet with the MHTML equivalent.
|
159
|
+
# The newlines ("\r\n") in the following method are critical. Without them
|
160
|
+
# your MHTML will look identical, but won't work.
|
161
|
+
def with_mhtml(css, asset_url)
|
162
|
+
paths, index = {}, 0
|
163
|
+
css = css.force_encoding('UTF-8').gsub(EMBED_REPLACER) do |url|
|
164
|
+
i = paths[$1] ||= "#{index += 1}-#{File.basename($1)}"
|
165
|
+
"url(mhtml:#{asset_url}!#{i})"
|
166
|
+
end
|
167
|
+
mhtml = paths.sort.map do |path, identifier|
|
168
|
+
mime, contents = mime_type(path), encoded_contents(path)
|
169
|
+
[MHTML_SEPARATOR, "Content-Location: #{identifier}\r\n", "Content-Type: #{mime}\r\n", "Content-Transfer-Encoding: base64\r\n\r\n", contents, "\r\n"]
|
170
|
+
end
|
171
|
+
[MHTML_START, mhtml, MHTML_END, css].flatten.join('')
|
172
|
+
end
|
173
|
+
|
174
|
+
# Return a rewritten asset URL for a new stylesheet -- the asset should
|
175
|
+
# be tagged for embedding if embeddable, and referenced at the correct level
|
176
|
+
# if relative.
|
177
|
+
def construct_asset_path(asset_path, css_path, variant)
|
178
|
+
public_path = absolute_path(asset_path, css_path)
|
179
|
+
return "__EMBED__#{public_path}" if embeddable?(public_path, variant)
|
180
|
+
source = asset_path.absolute? ? asset_path.to_s : relative_path(public_path)
|
181
|
+
rewrite_asset_path(source, public_path)
|
182
|
+
end
|
183
|
+
|
184
|
+
# Get the site-absolute public path for an asset file path that may or may
|
185
|
+
# not be relative, given the path of the stylesheet that contains it.
|
186
|
+
def absolute_path(asset_pathname, css_pathname)
|
187
|
+
(asset_pathname.absolute? ?
|
188
|
+
Pathname.new(File.join(PUBLIC_ROOT, asset_pathname)) :
|
189
|
+
css_pathname.dirname + asset_pathname).cleanpath
|
190
|
+
end
|
191
|
+
|
192
|
+
# CSS assets that are referenced by relative paths, and are *not* being
|
193
|
+
# embedded, must be rewritten relative to the newly-merged stylesheet path.
|
194
|
+
def relative_path(absolute_path)
|
195
|
+
File.join('../', absolute_path.sub(PUBLIC_ROOT, ''))
|
196
|
+
end
|
197
|
+
|
198
|
+
# Similar to the AssetTagHelper's method of the same name, this will
|
199
|
+
# append the RAILS_ASSET_ID cache-buster to URLs, if it's defined.
|
200
|
+
def rewrite_asset_path(path, file_path)
|
201
|
+
asset_id = rails_asset_id(file_path)
|
202
|
+
(!asset_id || asset_id == '') ? path : "#{path}?#{asset_id}"
|
203
|
+
end
|
204
|
+
|
205
|
+
# Similar to the AssetTagHelper's method of the same name, this will
|
206
|
+
# determine the correct asset id for a file.
|
207
|
+
def rails_asset_id(path)
|
208
|
+
asset_id = ENV["RAILS_ASSET_ID"]
|
209
|
+
return asset_id if asset_id
|
210
|
+
File.exists?(path) ? File.mtime(path).to_i.to_s : ''
|
211
|
+
end
|
212
|
+
|
213
|
+
# An asset is valid for embedding if it exists, is less than 32K, and is
|
214
|
+
# stored somewhere inside of a folder named "embed". IE does not support
|
215
|
+
# Data-URIs larger than 32K, and you probably shouldn't be embedding assets
|
216
|
+
# that large in any case. Because we need to check the base64 length here,
|
217
|
+
# save it so that we don't have to compute it again later.
|
218
|
+
def embeddable?(asset_path, variant)
|
219
|
+
font = EMBED_FONTS.include?(asset_path.extname)
|
220
|
+
return false unless variant
|
221
|
+
return false unless asset_path.to_s.match(EMBEDDABLE) && asset_path.exist?
|
222
|
+
return false unless EMBED_EXTS.include?(asset_path.extname)
|
223
|
+
return false unless font || encoded_contents(asset_path).length < MAX_IMAGE_SIZE
|
224
|
+
return false if font && variant == :mhtml
|
225
|
+
return true
|
226
|
+
end
|
227
|
+
|
228
|
+
# Return the Base64-encoded contents of an asset on a single line.
|
229
|
+
def encoded_contents(asset_path)
|
230
|
+
return @asset_contents[asset_path] if @asset_contents[asset_path]
|
231
|
+
data = read_binary_file(asset_path)
|
232
|
+
@asset_contents[asset_path] = Base64.encode64(data).gsub(/\n/, '')
|
233
|
+
end
|
234
|
+
|
235
|
+
# Grab the mime-type of an asset, by filename.
|
236
|
+
def mime_type(asset_path)
|
237
|
+
EMBED_MIME_TYPES[File.extname(asset_path)]
|
238
|
+
end
|
239
|
+
|
240
|
+
# Concatenate together a list of asset files.
|
241
|
+
def concatenate(paths)
|
242
|
+
[paths].flatten.map {|p| read_binary_file(p) }.join("\n")
|
243
|
+
end
|
244
|
+
|
245
|
+
# `File.read`, but in "binary" mode.
|
246
|
+
def read_binary_file(path)
|
247
|
+
File.open(path, 'r:binary') {|f| f.read }
|
248
|
+
end
|
249
|
+
end
|
250
|
+
|
251
|
+
end
|
@@ -0,0 +1,94 @@
|
|
1
|
+
module Jammit
|
2
|
+
|
3
|
+
# The JammitController is added to your Rails application when the Gem is
|
4
|
+
# loaded. It takes responsibility for /assets, and dynamically packages any
|
5
|
+
# missing or uncached asset packages.
|
6
|
+
class Controller < ActionController::Base
|
7
|
+
|
8
|
+
VALID_FORMATS = [:css, :js]
|
9
|
+
|
10
|
+
SUFFIX_STRIPPER = /-(datauri|mhtml)\Z/
|
11
|
+
|
12
|
+
NOT_FOUND_PATH = "#{PUBLIC_ROOT}/404.html"
|
13
|
+
|
14
|
+
# The "package" action receives all requests for asset packages that haven't
|
15
|
+
# yet been cached. The package will be built, cached, and gzipped.
|
16
|
+
def package
|
17
|
+
parse_request
|
18
|
+
case @extension
|
19
|
+
when :js
|
20
|
+
render :js => (@contents = Jammit.packager.pack_javascripts(@package))
|
21
|
+
when Jammit.template_extension.to_sym
|
22
|
+
render :js => (@contents = Jammit.packager.pack_templates(@package))
|
23
|
+
when :css
|
24
|
+
render :text => generate_stylesheets, :content_type => 'text/css'
|
25
|
+
end
|
26
|
+
cache_package if perform_caching
|
27
|
+
rescue Jammit::PackageNotFound
|
28
|
+
package_not_found
|
29
|
+
end
|
30
|
+
|
31
|
+
|
32
|
+
private
|
33
|
+
|
34
|
+
# Tells the Jammit::Packager to cache and gzip an asset package. We can't
|
35
|
+
# just use the built-in "cache_page" because we need to ensure that
|
36
|
+
# the timestamp that ends up in the MHTML is also on the cached file.
|
37
|
+
def cache_package
|
38
|
+
dir = File.join(page_cache_directory, Jammit.package_path)
|
39
|
+
Jammit.packager.cache(@package, @extension, @contents, dir, @variant, @mtime)
|
40
|
+
end
|
41
|
+
|
42
|
+
# Generate the complete, timestamped, MHTML url -- if we're rendering a
|
43
|
+
# dynamic MHTML package, we'll need to put one URL in the response, and a
|
44
|
+
# different one into the cached package.
|
45
|
+
def prefix_url(path)
|
46
|
+
host = request.port == 80 ? request.host : request.host_with_port
|
47
|
+
"#{request.protocol}#{host}#{path}"
|
48
|
+
end
|
49
|
+
|
50
|
+
# If we're generating MHTML/CSS, return a stylesheet with the absolute
|
51
|
+
# request URL to the client, and cache a version with the timestamped cache
|
52
|
+
# URL swapped in.
|
53
|
+
def generate_stylesheets
|
54
|
+
return @contents = Jammit.packager.pack_stylesheets(@package, @variant) unless @variant == :mhtml
|
55
|
+
@mtime = Time.now
|
56
|
+
request_url = prefix_url(request.fullpath)
|
57
|
+
cached_url = prefix_url(Jammit.asset_url(@package, @extension, @variant, @mtime))
|
58
|
+
css = Jammit.packager.pack_stylesheets(@package, @variant, request_url)
|
59
|
+
@contents = css.gsub(request_url, cached_url) if perform_caching
|
60
|
+
css
|
61
|
+
end
|
62
|
+
|
63
|
+
# Extracts the package name, extension (:css, :js), and variant (:datauri,
|
64
|
+
# :mhtml) from the incoming URL.
|
65
|
+
def parse_request
|
66
|
+
pack = params[:package]
|
67
|
+
@extension = params[:extension].to_sym
|
68
|
+
raise PackageNotFound unless (VALID_FORMATS + [Jammit.template_extension.to_sym]).include?(@extension)
|
69
|
+
if Jammit.embed_assets
|
70
|
+
suffix_match = pack.match(SUFFIX_STRIPPER)
|
71
|
+
@variant = Jammit.embed_assets && suffix_match && suffix_match[1].to_sym
|
72
|
+
pack.sub!(SUFFIX_STRIPPER, '')
|
73
|
+
end
|
74
|
+
@package = pack.to_sym
|
75
|
+
end
|
76
|
+
|
77
|
+
# Render the 404 page, if one exists, for any packages that don't.
|
78
|
+
def package_not_found
|
79
|
+
return render(:file => NOT_FOUND_PATH, :status => 404) if File.exists?(NOT_FOUND_PATH)
|
80
|
+
render :text => "<h1>404: \"#{@package}\" asset package not found.</h1>", :status => 404
|
81
|
+
end
|
82
|
+
|
83
|
+
end
|
84
|
+
|
85
|
+
end
|
86
|
+
|
87
|
+
# Make the Jammit::Controller available to Rails as a top-level controller.
|
88
|
+
::JammitController = Jammit::Controller
|
89
|
+
|
90
|
+
if defined?(Rails) && (Rails.env.development? || Rails.env.test?)
|
91
|
+
ActionController::Base.class_eval do
|
92
|
+
append_before_filter { Jammit.reload! }
|
93
|
+
end
|
94
|
+
end
|
@@ -0,0 +1,28 @@
|
|
1
|
+
# Standard Library Dependencies:
|
2
|
+
require 'uri'
|
3
|
+
require 'erb'
|
4
|
+
require 'zlib'
|
5
|
+
require 'yaml'
|
6
|
+
require 'base64'
|
7
|
+
require 'pathname'
|
8
|
+
require 'fileutils'
|
9
|
+
|
10
|
+
# Gem Dependencies:
|
11
|
+
require 'yui/compressor'
|
12
|
+
require 'closure-compiler'
|
13
|
+
|
14
|
+
# Load initial configuration before the rest of Jammit.
|
15
|
+
Jammit.load_configuration(Jammit::DEFAULT_CONFIG_PATH, true) if defined?(Rails)
|
16
|
+
|
17
|
+
# Jammit Core:
|
18
|
+
require 'jammit/compressor'
|
19
|
+
require 'jammit/packager'
|
20
|
+
|
21
|
+
# Jammit Rails Integration:
|
22
|
+
if defined?(Rails)
|
23
|
+
require 'jammit/controller'
|
24
|
+
require 'jammit/helper'
|
25
|
+
require 'jammit/railtie'
|
26
|
+
require 'jammit/routes'
|
27
|
+
end
|
28
|
+
|
@@ -0,0 +1,81 @@
|
|
1
|
+
module Jammit
|
2
|
+
|
3
|
+
# The Jammit::Helper module, which is made available to every view, provides
|
4
|
+
# helpers for writing out HTML tags for asset packages. In development you
|
5
|
+
# get the ordered list of source files -- in any other environment, a link
|
6
|
+
# to the cached packages.
|
7
|
+
module Helper
|
8
|
+
|
9
|
+
DATA_URI_START = "<!--[if (!IE)|(gte IE 8)]><!-->" unless defined?(DATA_URI_START)
|
10
|
+
DATA_URI_END = "<!--<![endif]-->" unless defined?(DATA_URI_END)
|
11
|
+
MHTML_START = "<!--[if lte IE 7]>" unless defined?(MHTML_START)
|
12
|
+
MHTML_END = "<![endif]-->" unless defined?(MHTML_END)
|
13
|
+
|
14
|
+
# If embed_assets is turned on, writes out links to the Data-URI and MHTML
|
15
|
+
# versions of the stylesheet package, otherwise the package is regular
|
16
|
+
# compressed CSS, and in development the stylesheet URLs are passed verbatim.
|
17
|
+
def include_stylesheets(*packages)
|
18
|
+
options = packages.extract_options!
|
19
|
+
return individual_stylesheets(packages, options) unless Jammit.package_assets
|
20
|
+
disabled = (options.delete(:embed_assets) == false) || (options.delete(:embed_images) == false)
|
21
|
+
return html_safe(packaged_stylesheets(packages, options)) if disabled || !Jammit.embed_assets
|
22
|
+
return html_safe(embedded_image_stylesheets(packages, options))
|
23
|
+
end
|
24
|
+
|
25
|
+
# Writes out the URL to the bundled and compressed javascript package,
|
26
|
+
# except in development, where it references the individual scripts.
|
27
|
+
def include_javascripts(*packages)
|
28
|
+
tags = packages.map do |pack|
|
29
|
+
Jammit.package_assets ? Jammit.asset_url(pack, :js) : Jammit.packager.individual_urls(pack.to_sym, :js)
|
30
|
+
end
|
31
|
+
html_safe(javascript_include_tag(tags.flatten))
|
32
|
+
end
|
33
|
+
|
34
|
+
# Writes out the URL to the concatenated and compiled JST file -- we always
|
35
|
+
# have to pre-process it, even in development.
|
36
|
+
def include_templates(*packages)
|
37
|
+
raise DeprecationError, "Jammit 0.5+ no longer supports separate packages for templates.\nYou can include your JST alongside your JS, and use include_javascripts."
|
38
|
+
end
|
39
|
+
|
40
|
+
|
41
|
+
private
|
42
|
+
|
43
|
+
def html_safe(string)
|
44
|
+
string.respond_to?(:html_safe) ? string.html_safe : string
|
45
|
+
end
|
46
|
+
|
47
|
+
# HTML tags, in order, for all of the individual stylesheets.
|
48
|
+
def individual_stylesheets(packages, options)
|
49
|
+
tags_with_options(packages, options) {|p| Jammit.packager.individual_urls(p.to_sym, :css) }
|
50
|
+
end
|
51
|
+
|
52
|
+
# HTML tags for the stylesheet packages.
|
53
|
+
def packaged_stylesheets(packages, options)
|
54
|
+
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css) }
|
55
|
+
end
|
56
|
+
|
57
|
+
# HTML tags for the 'datauri', and 'mhtml' versions of the packaged
|
58
|
+
# stylesheets, using conditional comments to load the correct variant.
|
59
|
+
def embedded_image_stylesheets(packages, options)
|
60
|
+
datauri_tags = tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :datauri) }
|
61
|
+
ie_tags = Jammit.mhtml_enabled ?
|
62
|
+
tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :mhtml) } :
|
63
|
+
packaged_stylesheets(packages, options)
|
64
|
+
[DATA_URI_START, datauri_tags, DATA_URI_END, MHTML_START, ie_tags, MHTML_END].join("\n")
|
65
|
+
end
|
66
|
+
|
67
|
+
# Generate the stylesheet tags for a batch of packages, with options, by
|
68
|
+
# yielding each package to a block.
|
69
|
+
def tags_with_options(packages, options)
|
70
|
+
packages = packages.dup
|
71
|
+
packages.map! {|package| yield package }.flatten!
|
72
|
+
packages.push(options) unless options.empty?
|
73
|
+
stylesheet_link_tag(*packages)
|
74
|
+
end
|
75
|
+
|
76
|
+
end
|
77
|
+
|
78
|
+
end
|
79
|
+
|
80
|
+
# Include the Jammit asset helpers in all views, a-la ApplicationHelper.
|
81
|
+
::ActionView::Base.send(:include, Jammit::Helper)
|
data/lib/jammit/jst.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
var template = function(str){var fn = new Function('obj', 'var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push(\''+str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^%]*%>)/g,"\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g,"',$1,'").split("<%").join("');").split("%>").join("p.push('")+"');}return p.join('');"); return fn;};
|
@@ -0,0 +1,162 @@
|
|
1
|
+
module Jammit
|
2
|
+
|
3
|
+
# The Jammit::Packager resolves the configuration file into lists of real
|
4
|
+
# assets that get merged into individual asset packages. Given the compiled
|
5
|
+
# contents of an asset package, the Packager knows how to cache that package
|
6
|
+
# with the correct timestamps.
|
7
|
+
class Packager
|
8
|
+
|
9
|
+
# In Rails, the difference between a path and an asset URL is "public".
|
10
|
+
PATH_DIFF = PUBLIC_ROOT.sub(ASSET_ROOT, '')
|
11
|
+
PATH_TO_URL = /\A#{Regexp.escape(ASSET_ROOT)}(\/?#{Regexp.escape(PATH_DIFF)})?/
|
12
|
+
|
13
|
+
# Set force to false to allow packages to only be rebuilt when their source
|
14
|
+
# files have changed since the last time their package was built.
|
15
|
+
attr_accessor :force
|
16
|
+
|
17
|
+
# Creating a new Packager will rebuild the list of assets from the
|
18
|
+
# Jammit.configuration. When assets.yml is being changed on the fly,
|
19
|
+
# create a new Packager.
|
20
|
+
def initialize
|
21
|
+
@compressor = Compressor.new
|
22
|
+
@force = false
|
23
|
+
@config = {
|
24
|
+
:css => (Jammit.configuration[:stylesheets] || {}),
|
25
|
+
:js => (Jammit.configuration[:javascripts] || {})
|
26
|
+
}
|
27
|
+
@packages = {
|
28
|
+
:css => create_packages(@config[:css]),
|
29
|
+
:js => create_packages(@config[:js])
|
30
|
+
}
|
31
|
+
end
|
32
|
+
|
33
|
+
# Ask the packager to precache all defined assets, along with their gzip'd
|
34
|
+
# versions. In order to prebuild the MHTML stylesheets, we need to know the
|
35
|
+
# base_url, because IE only supports MHTML with absolute references.
|
36
|
+
# Unless forced, will only rebuild assets whose source files have been
|
37
|
+
# changed since their last package build.
|
38
|
+
def precache_all(output_dir=nil, base_url=nil)
|
39
|
+
output_dir ||= File.join(PUBLIC_ROOT, Jammit.package_path)
|
40
|
+
cacheable(:js, output_dir).each {|p| cache(p, 'js', pack_javascripts(p), output_dir) }
|
41
|
+
cacheable(:css, output_dir).each do |p|
|
42
|
+
cache(p, 'css', pack_stylesheets(p), output_dir)
|
43
|
+
if Jammit.embed_assets
|
44
|
+
cache(p, 'css', pack_stylesheets(p, :datauri), output_dir, :datauri)
|
45
|
+
if Jammit.mhtml_enabled && base_url
|
46
|
+
mtime = Time.now
|
47
|
+
asset_url = "#{base_url}#{Jammit.asset_url(p, :css, :mhtml, mtime)}"
|
48
|
+
cache(p, 'css', pack_stylesheets(p, :mhtml, asset_url), output_dir, :mhtml, mtime)
|
49
|
+
end
|
50
|
+
end
|
51
|
+
end
|
52
|
+
end
|
53
|
+
|
54
|
+
# Caches a single prebuilt asset package and gzips it at the highest
|
55
|
+
# compression level. Ensures that the modification time of both both
|
56
|
+
# variants is identical, for web server caching modules, as well as MHTML.
|
57
|
+
def cache(package, extension, contents, output_dir, suffix=nil, mtime=Time.now)
|
58
|
+
FileUtils.mkdir_p(output_dir) unless File.exists?(output_dir)
|
59
|
+
raise OutputNotWritable, "Jammit doesn't have permission to write to \"#{output_dir}\"" unless File.writable?(output_dir)
|
60
|
+
files = []
|
61
|
+
files << file_name = File.join(output_dir, Jammit.filename(package, extension, suffix))
|
62
|
+
File.open(file_name, 'wb+') {|f| f.write(contents) }
|
63
|
+
if Jammit.gzip_assets
|
64
|
+
files << zip_name = "#{file_name}.gz"
|
65
|
+
Zlib::GzipWriter.open(zip_name, Zlib::BEST_COMPRESSION) {|f| f.write(contents) }
|
66
|
+
end
|
67
|
+
File.utime(mtime, mtime, *files)
|
68
|
+
end
|
69
|
+
|
70
|
+
# Get the list of individual assets for a package.
|
71
|
+
def individual_urls(package, extension)
|
72
|
+
package_for(package, extension)[:urls]
|
73
|
+
end
|
74
|
+
|
75
|
+
# Return the compressed contents of a stylesheet package.
|
76
|
+
def pack_stylesheets(package, variant=nil, asset_url=nil)
|
77
|
+
@compressor.compress_css(package_for(package, :css)[:paths], variant, asset_url)
|
78
|
+
end
|
79
|
+
|
80
|
+
# Return the compressed contents of a javascript package.
|
81
|
+
def pack_javascripts(package)
|
82
|
+
@compressor.compress_js(package_for(package, :js)[:paths])
|
83
|
+
end
|
84
|
+
|
85
|
+
# Return the compiled contents of a JST package.
|
86
|
+
def pack_templates(package)
|
87
|
+
@compressor.compile_jst(package_for(package, :js)[:paths])
|
88
|
+
end
|
89
|
+
|
90
|
+
private
|
91
|
+
|
92
|
+
# Look up a package asset list by name, raising an exception if the
|
93
|
+
# package has gone missing.
|
94
|
+
def package_for(package, extension)
|
95
|
+
pack = @packages[extension] && @packages[extension][package]
|
96
|
+
pack || not_found(package, extension)
|
97
|
+
end
|
98
|
+
|
99
|
+
# Absolute globs are absolute -- relative globs are relative to ASSET_ROOT.
|
100
|
+
# Print a warning if no files were found that match the glob.
|
101
|
+
def glob_files(glob)
|
102
|
+
absolute = Pathname.new(glob).absolute?
|
103
|
+
paths = Dir[absolute ? glob : File.join(ASSET_ROOT, glob)].sort
|
104
|
+
Jammit.warn("No assets match '#{glob}'") if paths.empty?
|
105
|
+
paths
|
106
|
+
end
|
107
|
+
|
108
|
+
# Return a list of all of the packages that should be cached. If "force" is
|
109
|
+
# true, this is all of them -- otherwise only the packages that are missing
|
110
|
+
# or whose source files have changed since the last package build.
|
111
|
+
def cacheable(extension, output_dir)
|
112
|
+
names = @packages[extension].keys
|
113
|
+
return names if @force
|
114
|
+
config_mtime = File.mtime(Jammit.config_path)
|
115
|
+
return names.select do |name|
|
116
|
+
pack = package_for(name, extension)
|
117
|
+
cached = [Jammit.filename(name, extension)]
|
118
|
+
cached.push Jammit.filename(name, extension, :datauri) if Jammit.embed_assets
|
119
|
+
cached.push Jammit.filename(name, extension, :mhtml) if Jammit.mhtml_enabled
|
120
|
+
cached.map! {|file| File.join(output_dir, file) }
|
121
|
+
if cached.any? {|file| !File.exists?(file) }
|
122
|
+
true
|
123
|
+
else
|
124
|
+
since = cached.map {|file| File.mtime(file) }.min
|
125
|
+
config_mtime > since || pack[:paths].any? {|src| File.mtime(src) > since }
|
126
|
+
end
|
127
|
+
end
|
128
|
+
end
|
129
|
+
|
130
|
+
# Compiles the list of assets that goes into each package. Runs an
|
131
|
+
# ordered list of Dir.globs, taking the merged unique result.
|
132
|
+
# If there are JST files in this package we need to add an extra
|
133
|
+
# path for when package_assets is off (e.g. in a dev environment).
|
134
|
+
# This package (e.g. /assets/package-name.jst) will never exist as
|
135
|
+
# an actual file but will be dynamically generated by Jammit on
|
136
|
+
# every request.
|
137
|
+
def create_packages(config)
|
138
|
+
packages = {}
|
139
|
+
return packages if !config
|
140
|
+
config.each do |name, globs|
|
141
|
+
globs ||= []
|
142
|
+
packages[name] = {}
|
143
|
+
paths = globs.flatten.uniq.map {|glob| glob_files(glob) }.flatten.uniq
|
144
|
+
packages[name][:paths] = paths
|
145
|
+
if !paths.grep(Jammit.template_extension_matcher).empty?
|
146
|
+
packages[name][:urls] = paths.grep(JS_EXTENSION).map {|path| path.sub(PATH_TO_URL, '') }
|
147
|
+
packages[name][:urls] += [Jammit.asset_url(name, Jammit.template_extension)]
|
148
|
+
else
|
149
|
+
packages[name][:urls] = paths.map {|path| path.sub(PATH_TO_URL, '') }
|
150
|
+
end
|
151
|
+
end
|
152
|
+
packages
|
153
|
+
end
|
154
|
+
|
155
|
+
# Raise a PackageNotFound exception for missing packages...
|
156
|
+
def not_found(package, extension)
|
157
|
+
raise PackageNotFound, "assets.yml does not contain a \"#{package}\" #{extension.to_s.upcase} package"
|
158
|
+
end
|
159
|
+
|
160
|
+
end
|
161
|
+
|
162
|
+
end
|
@@ -0,0 +1,14 @@
|
|
1
|
+
# Rails 3 configuration via Railtie
|
2
|
+
|
3
|
+
if defined?(Rails::Railtie)
|
4
|
+
module Jammit
|
5
|
+
class Railtie < Rails::Railtie
|
6
|
+
|
7
|
+
initializer :jammit_routes do |app|
|
8
|
+
# Add a Jammit route for the reloader.
|
9
|
+
app.routes_reloader.paths << File.join(File.dirname(__FILE__), "..", "..", "rails", "routes.rb")
|
10
|
+
end
|
11
|
+
|
12
|
+
end
|
13
|
+
end
|
14
|
+
end
|
@@ -0,0 +1,23 @@
|
|
1
|
+
module Jammit
|
2
|
+
|
3
|
+
# Rails 2.x routing module. Rails 3.x routes are in rails/routes.rb.
|
4
|
+
module Routes
|
5
|
+
|
6
|
+
# Jammit uses a single route in order to slow down Rails' routing speed
|
7
|
+
# by the absolute minimum. In your config/routes.rb file, call:
|
8
|
+
# Jammit::Routes.draw(map)
|
9
|
+
# Passing in the routing "map" object.
|
10
|
+
def self.draw(map)
|
11
|
+
map.jammit "/#{Jammit.package_path}/:package.:extension", {
|
12
|
+
:controller => 'jammit',
|
13
|
+
:action => 'package',
|
14
|
+
:requirements => {
|
15
|
+
# A hack to allow extension to include "."
|
16
|
+
:extension => /.+/
|
17
|
+
}
|
18
|
+
}
|
19
|
+
end
|
20
|
+
|
21
|
+
end
|
22
|
+
|
23
|
+
end
|
data/rails/routes.rb
ADDED
@@ -0,0 +1,10 @@
|
|
1
|
+
if defined?(Rails::Application)
|
2
|
+
# Rails3 routes
|
3
|
+
Rails.application.routes.draw do
|
4
|
+
match "/#{Jammit.package_path}/:package.:extension",
|
5
|
+
:to => 'jammit#package', :as => :jammit, :constraints => {
|
6
|
+
# A hack to allow extension to include "."
|
7
|
+
:extension => /.+/
|
8
|
+
}
|
9
|
+
end
|
10
|
+
end
|
metadata
ADDED
@@ -0,0 +1,95 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: moxiesoft-jammit
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
prerelease:
|
5
|
+
version: 0.5.4
|
6
|
+
platform: ruby
|
7
|
+
authors:
|
8
|
+
- Jeremy Ashkenas
|
9
|
+
autorequire:
|
10
|
+
bindir: bin
|
11
|
+
cert_chain: []
|
12
|
+
|
13
|
+
date: 2010-08-11 00:00:00 Z
|
14
|
+
dependencies:
|
15
|
+
- !ruby/object:Gem::Dependency
|
16
|
+
name: yui-compressor
|
17
|
+
prerelease: false
|
18
|
+
requirement: &id001 !ruby/object:Gem::Requirement
|
19
|
+
none: false
|
20
|
+
requirements:
|
21
|
+
- - ">="
|
22
|
+
- !ruby/object:Gem::Version
|
23
|
+
version: 0.9.1
|
24
|
+
type: :runtime
|
25
|
+
version_requirements: *id001
|
26
|
+
- !ruby/object:Gem::Dependency
|
27
|
+
name: closure-compiler
|
28
|
+
prerelease: false
|
29
|
+
requirement: &id002 !ruby/object:Gem::Requirement
|
30
|
+
none: false
|
31
|
+
requirements:
|
32
|
+
- - ">="
|
33
|
+
- !ruby/object:Gem::Version
|
34
|
+
version: 0.1.0
|
35
|
+
type: :runtime
|
36
|
+
version_requirements: *id002
|
37
|
+
description: " Jammit is an industrial strength asset packaging library for Rails,\n providing both the CSS and JavaScript concatenation and compression that\n you'd expect, as well as YUI Compressor and Closure Compiler compatibility,\n ahead-of-time gzipping, built-in JavaScript template support, and optional\n Data-URI / MHTML image embedding.\n"
|
38
|
+
email: jeremy@documentcloud.org
|
39
|
+
executables:
|
40
|
+
- jammit
|
41
|
+
extensions: []
|
42
|
+
|
43
|
+
extra_rdoc_files:
|
44
|
+
- README
|
45
|
+
files:
|
46
|
+
- lib/jammit/command_line.rb
|
47
|
+
- lib/jammit/compressor.rb
|
48
|
+
- lib/jammit/controller.rb
|
49
|
+
- lib/jammit/dependencies.rb
|
50
|
+
- lib/jammit/helper.rb
|
51
|
+
- lib/jammit/jst.js
|
52
|
+
- lib/jammit/packager.rb
|
53
|
+
- lib/jammit/railtie.rb
|
54
|
+
- lib/jammit/routes.rb
|
55
|
+
- lib/jammit.rb
|
56
|
+
- bin/jammit
|
57
|
+
- rails/routes.rb
|
58
|
+
- jammit.gemspec
|
59
|
+
- LICENSE
|
60
|
+
- README
|
61
|
+
homepage: http://documentcloud.github.com/jammit/
|
62
|
+
licenses: []
|
63
|
+
|
64
|
+
post_install_message:
|
65
|
+
rdoc_options:
|
66
|
+
- --title
|
67
|
+
- Jammit
|
68
|
+
- --exclude
|
69
|
+
- test
|
70
|
+
- --main
|
71
|
+
- README
|
72
|
+
- --all
|
73
|
+
require_paths:
|
74
|
+
- lib
|
75
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
76
|
+
none: false
|
77
|
+
requirements:
|
78
|
+
- - ">="
|
79
|
+
- !ruby/object:Gem::Version
|
80
|
+
version: "0"
|
81
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
82
|
+
none: false
|
83
|
+
requirements:
|
84
|
+
- - ">="
|
85
|
+
- !ruby/object:Gem::Version
|
86
|
+
version: "0"
|
87
|
+
requirements: []
|
88
|
+
|
89
|
+
rubyforge_project: jammit
|
90
|
+
rubygems_version: 1.7.2
|
91
|
+
signing_key:
|
92
|
+
specification_version: 3
|
93
|
+
summary: Industrial Strength Asset Packaging for Rails
|
94
|
+
test_files: []
|
95
|
+
|