Class: Adva::Rack::Static

Inherits:
Object
  • Object
show all
Defined in:
lib/adva/rack/static.rb

Constant Summary collapse

FILE_METHODS =
%w(GET HEAD)
STATIC_PATHS =
%w(/images/adva /javascripts/adva /stylesheets/adva)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Static

Returns a new instance of Static.



11
12
13
14
# File 'lib/adva/rack/static.rb', line 11

def initialize(app)
  @app = app
  @directories = Adva.engines.map { |engine| ::Rack::File.new(engine.root.join('public')) }
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



9
10
11
# File 'lib/adva/rack/static.rb', line 9

def app
  @app
end

#directoriesObject (readonly)

Returns the value of attribute directories.



9
10
11
# File 'lib/adva/rack/static.rb', line 9

def directories
  @directories
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/adva/rack/static.rb', line 16

def call(env)
  path   = env['PATH_INFO'].chomp('/')
  method = env['REQUEST_METHOD']

  if FILE_METHODS.include?(method) && static?(path)
    if directory = directories.detect { |directory| exist?(directory, path) }
      return directory.call(env)
    else
      return not_found(path)
    end
  end

  app.call(env)
end

#exist?(directory, path) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/adva/rack/static.rb', line 35

def exist?(directory, path)
  File.file?(File.join(directory.root, ::Rack::Utils.unescape(path)))
end

#not_found(path) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/adva/rack/static.rb', line 39

def not_found(path)
  body = "File not found: #{path}\n"
  headers = {
    'Content-Type'   => 'text/plain',
    'Content-Length' => body.size.to_s,
    'X-Cascade'      => 'pass'
  }
  [404, headers, [body]]
end

#static?(path) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/adva/rack/static.rb', line 31

def static?(path)
  STATIC_PATHS.detect { |static_path| path.starts_with?(static_path)  }
end