Class: Rack::Fonts

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-fonts.rb

Overview

This middleware merely wraps the Rack::Static one so it admits the same options:

:root => "public"
looks for all the assets under the `public` subdirectory of the current directory

:urls => ["/assets"]
intercepts the requests beginning with `/media` and tries to serve static files
from the directory specified by the `root` option.
(Note that you can indicate more that one URL in the `urls` option)

So, for instance:

use Rack::Assets :root => 'public', :urls => ['/assets']

will respond to a request path `/assets/images/nelson.gif`
with the file located in `./public/images/nelson.gif`

In addition, `Rack::Assets` supports a `:cache_time` option to easily indicate
a cache expiration for your assets.

Apart from that, it will return appropiate `Content-Type` for webfonts and will
add set the `Access-Control-Allow-Origin` header to `*`, so strict browsers like
Firefox will be able to use these assets from different sites.

Constant Summary collapse

VERSION =
'0.1.1'

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Fonts

Returns a new instance of Fonts.



33
34
35
36
37
38
# File 'lib/rack-fonts.rb', line 33

def initialize(app, options = {})
  @original_app = app
  @urls = options[:urls] || ["/favicon.ico"]
  @cache_time = options.delete(:cache_time) || 31536000 # 1 year in seconds
  @statics_app = ::Rack::Static.new(@original_app, options)
end

Instance Method Details

#call(env) ⇒ Object



40
41
42
# File 'lib/rack-fonts.rb', line 40

def call(env)
  static?(env) ? serve_static(env) : @original_app.call(env)
end

#content_type_for_extension(ext) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/rack-fonts.rb', line 60

def content_type_for_extension(ext)
  {
    :ttf => 'font/truetype',
    :otf => 'font/opentype',
    :woff => 'application/x-font-woff',
    :eot =>  'application/vnd.ms-fontobject',
    :svg =>  'image/svg+xml'
  }[ext.to_sym]
end

#serve_static(env) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rack-fonts.rb', line 48

def serve_static(env)
  status, headers, body = @statics_app.call(env)

  headers['Cache-Control'] = "public, max-age=#{@cache_time}"
  headers['Expires'] = (Time.now + @cache_time).httpdate
  headers['Access-Control-Allow-Origin'] = '*'

  _, ext = env['PATH_INFO'].match(/\.(\w+)$/).to_a
  (headers['Content-Type'] = content_type_for_extension(ext) || headers['Content-Type']) if ext
  [status, headers, body]
end

#static?(env) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/rack-fonts.rb', line 44

def static?(env)
  @urls.any?{ |url| env["PATH_INFO"].index(url) == 0 }
end