Module: Sinatra::AssetPack::Compressor

Extended by:
Compressor
Included in:
Compressor
Defined in:
lib/sinatra/assetpack/compressor.rb

Instance Method Summary collapse

Instance Method Details

#compress(str, type, engine = nil, options = {}) ⇒ Object

Compresses a given string.

compress File.read('x.js'), :js, :jsmin

Raises:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/sinatra/assetpack/compressor.rb', line 10

def compress(str, type, engine=nil, options={})
  # Use defaults if no engine is given.
  return fallback(str, type, options)  if engine.nil?

  # Ensure that the engine exists.
  klass = compressors[[type, engine]]
  raise Error, "Engine #{engine} (#{type}) doesn't exist."  unless klass

  # Ensure that the engine can support that type.
  engine = klass.new
  raise Error, "#{klass} does not support #{type.upcase} compression."  unless engine.respond_to?(type)

  # Build it using the engine, and fallback to defaults if it fails.
  output   = engine.send type, str, options
  output ||= fallback(str, type, options)  unless options[:no_fallback]
  output
end

#compressorsObject



37
38
39
# File 'lib/sinatra/assetpack/compressor.rb', line 37

def compressors
  @compressors ||= Hash.new
end

#fallback(str, type, options) ⇒ Object

Compresses a given string using the default engines.



29
30
31
32
33
34
35
# File 'lib/sinatra/assetpack/compressor.rb', line 29

def fallback(str, type, options)
  if type == :js
    compress str, :js, :jsmin, :no_fallback => true
  elsif type == :css
    compress str, :css, :simple, :no_fallback => true
  end
end

#register(type, engine, meth) ⇒ Object



41
42
43
# File 'lib/sinatra/assetpack/compressor.rb', line 41

def register(type, engine, meth)
  compressors[[type, engine]] = meth
end