Class: ServeThis::App

Inherits:
Object
  • Object
show all
Defined in:
lib/serve-this.rb

Overview

this does the file serving

Constant Summary collapse

FORBIDDEN_REGEXP =

prohibit showing system files

/^(\.|config.ru$|Gemfile$|Gemfile.lock$)/i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ App

Returns a new instance of App.



22
23
24
25
26
27
28
# File 'lib/serve-this.rb', line 22

def initialize(root)
  @root = root
  @file_server = ::Rack::File.new(root)
  
  res_path = ::File.join(::File.dirname(__FILE__), "..", "res")
  @res_server  = ::Rack::File.new(::File.expand_path(res_path))
end

Instance Attribute Details

#file_serverObject (readonly)

Returns the value of attribute file_server.



29
30
31
# File 'lib/serve-this.rb', line 29

def file_server
  @file_server
end

#res_serverObject (readonly)

Returns the value of attribute res_server.



29
30
31
# File 'lib/serve-this.rb', line 29

def res_server
  @res_server
end

#rootObject (readonly)

Returns the value of attribute root.



29
30
31
# File 'lib/serve-this.rb', line 29

def root
  @root
end

Instance Method Details

#call(env) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/serve-this.rb', line 31

def call(env)
  path = env["PATH_INFO"]

  if forbid?(path)
    forbid!
  else

    # if we are looking at / lets try index.html
    if path == "/" && exists?("index.html")
      env["PATH_INFO"] = "/index.html"
    elsif path == "/favicon.ico" && !exists?("favicon.ico")
      return self.res_server.call(env)
    elsif !exists?(path) && exists?(path+".html")
      env["PATH_INFO"] += ".html"
    elsif exists?(path) && directory?(path) && exists?(File.join(path, "index.html"))
      env["PATH_INFO"] += "/index.html"
    end
    
    self.file_server.call(env)
  end
end

#directory?(path) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/serve-this.rb', line 57

def directory?(path)
  File.directory?(File.join(self.root, path))
end

#exists?(path) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/serve-this.rb', line 53

def exists?(path)
  File.exist?(File.join(self.root, path))
end

#forbid!Object



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/serve-this.rb', line 73

def forbid!
  body = "Forbidden\n"
  status = 403
  [
    status,
    {
      "Content-Type" => "text/plain",
      "Content-Length" => body.size.to_s,
      "X-Cascade" => "pass"
    },
    [body]
  ]
end

#forbid?(path) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
68
69
70
71
# File 'lib/serve-this.rb', line 64

def forbid?(path)
  unescaped_path = ::Rack::Utils.unescape(path)
  if unescaped_path.start_with?("/")
    unescaped_path = unescaped_path[1..-1]
  end
  
  unescaped_path =~ FORBIDDEN_REGEXP
end