Created
October 22, 2010 13:52
-
-
Save rstacruz/640563 to your computer and use it in GitHub Desktop.
3.rb
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
-# Super cheapo minification! | |
-# Here's how it works: | |
-# | |
-# * The HAML below points to the minified version on production, | |
-# or prints <script> tags if not. | |
-# | |
-# * We define the route to /js/script.js ourselves. | |
-# | |
-# * Some silly caching will ensure that the minification only happens once. | |
- if settings.production? | |
%script{:type => 'text/javascript', :src => '/js/script.js?%s' % [settings.js_files.mtime.to_i] } | |
- else | |
- settings.js_files.hrefs.each do |href| | |
%script{:type => 'text/javascript', :src => href} |
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
path = settings.root_path(%w(public js)) | |
files = Dir["#{path}/jquery.*.js"] | |
files += Dir["#{path}/lib.*.js"] | |
files += Dir["#{path}/admin.js"] | |
files += Dir["#{path}/admin.*.js"] | |
# Here's the magic. | |
Main.set :js_files, JsFiles.new(files) | |
class Main | |
# This serves the minified JS. | |
get '/js/script.js' do | |
js = settings.admin_js | |
content_type :js | |
last_modified js.mtime | |
etag js.mtime.to_i | |
cache_control :public, :must_revalidate, :max_age => 86400 | |
js.compressed | |
end | |
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
# This class represents a list of JS files. | |
# Take note of how #compressed is implemented: it means that | |
# the files will always only be compressed once. | |
class JsFiles | |
attr_accessor :files | |
def initialize(files, options={}) | |
@files, @options = files, options | |
@options[:prefix] ||= '/js/' | |
end | |
def mtime | |
@mtime ||= @files.map { |f| File.mtime(f) }.max | |
end | |
def combined | |
@combined ||= @files.map { |file| File.open(file) { |f| f.read } }.join("\n") | |
end | |
def compressed | |
require 'jsmin' | |
@compressed ||= JSMin.minify(combined).strip | |
end | |
def hrefs | |
@files.map { |f| @options[:prefix] + File.basename(f) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment