Sha256: 578cd95b8af0aac70e7ba9a847185eda0e2237d56e9dccc5072a9a88eb689ba0

Contents?: true

Size: 1.34 KB

Versions: 7

Compression:

Stored size: 1.34 KB

Contents

##
# Fake response for dealing with file:/// requests

class Mechanize::FileResponse

  def initialize(file_path)
    @file_path = file_path
    @uri       = nil
  end

  def read_body
    raise Mechanize::ResponseCodeError.new(self) unless
      File.exist? @file_path

    if directory?
      yield dir_body
    else
      open @file_path, 'rb' do |io|
        yield io.read
      end
    end
  end

  def code
    File.exist?(@file_path) ? 200 : 404
  end

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

  def each_header; end

  def [](key)
    return nil if key.casecmp('Content-Type') != 0
    return 'text/html' if directory?
    return 'text/html' if ['.html', '.xhtml'].any? { |extn|
      @file_path.end_with?(extn)
    }
    nil
  end

  def each
  end

  def get_fields(key)
    []
  end

  def http_version
    '0'
  end

  def message
    File.exist?(@file_path) ? 'OK' : 'Not Found'
  end

  def uri
    @uri ||= URI "file://#{@file_path}"
  end

  private

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

    body.join("\n").force_encoding(Encoding::BINARY)
  end

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

end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
husc-0.2.1 vendor/bundle/gems/mechanize-2.7.6/lib/mechanize/file_response.rb
husc-0.2.0 vendor/bundle/gems/mechanize-2.7.6/lib/mechanize/file_response.rb
husc-0.1.1 vendor/bundle/gems/mechanize-2.7.6/lib/mechanize/file_response.rb
husc-0.1.0 vendor/bundle/gems/mechanize-2.7.6/lib/mechanize/file_response.rb
mechanize-2.7.6 lib/mechanize/file_response.rb
mechanize-2.7.5 lib/mechanize/file_response.rb
mechanize-2.7.4 lib/mechanize/file_response.rb