Skip to content

Commit 2f6e389

Browse files
committed
Make compressors lazily load.
1 parent 86390c3 commit 2f6e389

File tree

4 files changed

+40
-3
lines changed

4 files changed

+40
-3
lines changed

Gemfile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ end
1010

1111
gem "coffee-script"
1212
gem "sass"
13-
gem "uglifier", ">= 1.0.0"
13+
14+
# This needs to be with require false to avoid
15+
# it being automatically loaded by sprockets
16+
gem "uglifier", ">= 1.0.0", :require => false
1417

1518
gem "rake", ">= 0.8.7"
1619
gem "mocha", ">= 0.9.8"
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
module Sprockets
2+
class NullCompressor
3+
def compress(content)
4+
content
5+
end
6+
end
7+
8+
class LazyCompressor
9+
def initialize(&block)
10+
@block = block
11+
end
12+
13+
def compressor
14+
@compressor ||= @block.call || NullCompressor.new
15+
end
16+
17+
def compress(content)
18+
compressor.compress(content)
19+
end
20+
end
21+
end

actionpack/lib/sprockets/railtie.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
module Sprockets
22
autoload :Helpers, "sprockets/helpers"
3+
autoload :LazyCompressor, "sprockets/compressors"
4+
autoload :NullCompressor, "sprockets/compressors"
35

46
# TODO: Get rid of config.assets.enabled
57
class Railtie < ::Rails::Railtie
@@ -66,8 +68,8 @@ def asset_environment(app)
6668
if assets.compress
6769
# temporarily hardcode default JS compressor to uglify. Soon, it will work
6870
# the same as SCSS, where a default plugin sets the default.
69-
env.js_compressor = expand_js_compressor(assets.js_compressor || :uglifier)
70-
env.css_compressor = expand_css_compressor(assets.css_compressor)
71+
env.js_compressor = LazyCompressor.new { expand_js_compressor(assets.js_compressor || :uglifier) }
72+
env.css_compressor = LazyCompressor.new { expand_css_compressor(assets.css_compressor) }
7173
end
7274

7375
env

railties/test/application/assets_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ def app
3535
assert_match "alert()", last_response.body
3636
end
3737

38+
test "assets do not require compressors until it is used" do
39+
app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
40+
ENV["RAILS_ENV"] = "production"
41+
require "#{app_path}/config/environment"
42+
43+
assert !defined?(Uglifier)
44+
get "/assets/demo.js"
45+
assert_match "alert()", last_response.body
46+
assert defined?(Uglifier)
47+
end
48+
3849
test "assets are compiled properly" do
3950
app_file "app/assets/javascripts/application.js", "alert();"
4051
app_file "app/assets/javascripts/foo/application.js", "alert();"

0 commit comments

Comments
 (0)