Class: Pancake::Middlewares::Static

Inherits:
Object
  • Object
show all
Defined in:
lib/pancake/middlewares/static.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, stack) ⇒ Static

Returns a new instance of Static.



5
6
7
8
9
10
# File 'lib/pancake/middlewares/static.rb', line 5

def initialize(app, stack)
  @app, @stack = app, stack
  unless Pancake::Paths === stack
    raise "#{self.class} needs to be initialized with a stack (or something including Pancake::Paths)"
  end
end

Instance Attribute Details

#appObject

Returns the value of attribute app.



4
5
6
# File 'lib/pancake/middlewares/static.rb', line 4

def app
  @app
end

#stackObject

Returns the value of attribute stack.



4
5
6
# File 'lib/pancake/middlewares/static.rb', line 4

def stack
  @stack
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pancake/middlewares/static.rb', line 12

def call(env)
  static_file = nil
  root = stack.dirs_for(:public).detect do |root|
    root = File.expand_path(root)
    file_name = Rack::Utils.unescape(File.expand_path(File.join(root, env['PATH_INFO'].chomp("/"))))

    # If the client is asking for files outside the public directory, return missing
    # i.e. get "/../../foo.secret"
    if file_name !~ /^#{root}/
      return Rack::Response.new("Not Found", 404).finish
    end

    # If we get to here and the file exists serve it
    if File.file?(file_name)
      static_file = file_name
    end
  end

  if static_file
    Rack::Response.new(File.open(static_file), 200, {
      'Content-Type' => Rack::Mime.mime_type(File.extname(static_file))
    }).finish
  else
    app.call(env)
  end
end