Module: Sinatra::CompressedJS
- Defined in:
- lib/sinatra/support/compressedjs.rb
Overview
Serves compressed JS.
Usage example
Assuming you have JavaScript files stored in ./app/js
, and you want to serve the compressed JS in yoursite.com/js/compressed.js
:
# CompressedJS is recommended to be used alongside JsSupport to serve
# raw JS files in development mode. This will make your /app/js/*.js
# accessible via http://yoursite.com/js/*.js.
register Sinatra::JsSupport
serve_js '/js', from: './app/js'
register Sinatra::CompressedJS # Load the CompressedJS plugin
serve_compressed_js :app_js, # The name (used later in your views)
:prefix => '/js', # Where the individual JS files can be accessed at
:root => './app/js', # The root of your JS files
:path => '/js/compressed.js', # The URL where the compressed JS will served at
:files => # List of files
Dir['./app/js/vendor/*.js'] +
Dir['./app/js/app/**.js']
Note that :prefix
and :root
are the same things passed onto serve_js.
In your template view, add this before </body>: (The name app_js
comes from the first parameter passed to #serve_compressed_js.)
<%= settings.app_js.to_html %>
Example output
In development mode, this will probably output:
<script src='/js/vendor/jquery.js?1293847189'></script>
<script src='/js/app/application.js?1293847189'></script>
<!-- This is {:prefix} + {files, stripped of :root} -->
But in production mode:
<script src='/js/compressed.js?1293847189'></script>
<!-- This is {:path} given in serve_compressed_js -->
Caveats
You will need the JsMin gem.
# Gemfile
gem "jsmin", "~> 1.0.1"
CompressedJS supports CoffeeScript. If you do use CoffeeScript, be sure to add the approprate gem to your project.
# Gemfile
gem "coffee-script", require: "coffee_script"
More functions
Doing settings.app_js
returns a JsFiles instance. See the JsFiles class for more info on things you can do.
Caching
CompressedJS will cache compressed and combined scripts. This means that compression will only happen once in your application’s runtime.
Why no support for CSS compression?
If you use Sass/SCSS anyway, you can achieve the same thing by changing Sass’s :output settings to :compressed. If you also use @import in Sass/SCSS, you can easily consolidate all CSS into one file without any need for a Sinatra plugin.
Extending with another JS compressor
This is unsupported, but you may change the JsFiles.compress function to use something else.
# Sample custom compression (probably doesn't work)
def JsFiles.compress(str)
file = Tempfile.new { |f| f.write str }
output = Tempfile.new
system "closure-compiler #{file.path} #{output.path}"
output.read
end
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.registered(app) ⇒ Object
90 91 92 |
# File 'lib/sinatra/support/compressedjs.rb', line 90 def self.registered(app) app.set :jsfiles_cache_max_age, 86400*30 unless app.respond_to?(:jsfile_cache_max_age) end |