Module: Roda::RodaPlugins::SendFile::InstanceMethods

Defined in:
lib/roda/plugins/send_file.rb

Instance Method Summary collapse

Instance Method Details

#send_file(path, opts = OPTS) ⇒ Object

Use the contents of the file at path as the response body. See plugin documentation for options.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/roda/plugins/send_file.rb', line 71

def send_file(path, opts = OPTS)
  r = @_request
  res = @_response
  headers = res.headers
  if (type = opts[:type]) || !headers[RodaResponseHeaders::CONTENT_TYPE]
    type_str = type.to_s

    if type_str.include?('/')
      type = type_str
    else
      if type
        type = ".#{type}" unless type_str.start_with?(".")
      else
        type = ::File.extname(path)
      end

      type &&= Rack::Mime.mime_type(type, nil)
      type ||= 'application/octet-stream'
    end
    
    headers[RodaResponseHeaders::CONTENT_TYPE] = type
  end

  disposition = opts[:disposition]
  filename    = opts[:filename]
  if disposition || filename
    disposition ||= 'attachment'
    filename = path if filename.nil?
    res.attachment(filename, disposition)
  end

  if lm = opts[:last_modified]
    r.last_modified(lm)
  end

  file = RACK_FILES.new nil
  s, h, b = if Rack.release > '2'
    file.serving(r, path)
  else
    file.path = path
    file.serving(env)
  end

  res.status = opts[:status] || s
  headers.delete(RodaResponseHeaders::CONTENT_LENGTH)
  headers.replace(h.merge!(headers))
  r.halt res.finish_with_body(b)
rescue Errno::ENOENT
  response.status = 404
  r.halt
end