File: file_response.rb

package info (click to toggle)
libwww-mechanize-ruby 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 956 kB
  • ctags: 883
  • sloc: ruby: 6,621; makefile: 4
file content (60 lines) | stat: -rw-r--r-- 1,193 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Mechanize
  ###
  # Fake response for dealing with file:/// requests
  class FileResponse
    def initialize(file_path)
      @file_path = file_path
    end

    def read_body
      if ::File.exists?(@file_path)
        if directory?
          yield dir_body
        else
          yield ::File.read(@file_path)
        end
      else
        yield ''
      end
    end

    def code
      ::File.exists?(@file_path) ? 200 : 400
    end

    def content_length
      return dir_body.length if directory?
      ::File.exists?(@file_path) ? ::File.stat(@file_path).size : 0
    end

    def each_header; end

    def [](key)
      return nil unless key.downcase == 'content-type'
      return 'text/html' if directory?
      return 'text/html' if ['.html', '.xhtml'].any? { |extn|
        @file_path =~ /#{extn}$/
      }
      nil
    end

    def each
    end

    def get_fields(key)
      []
    end

    private
    def dir_body
      '<html><body>' +
        Dir[::File.join(@file_path, '*')].map { |f|
        "<a href=\"file://#{f}\">#{::File.basename(f)}</a>"
      }.join("\n") + '</body></html>'
    end

    def directory?
      ::File.directory?(@file_path)
    end
  end
end