Method: MongoidExt::File#put

Defined in:
lib/mongoid_ext/file.rb

#put(filename, io, options = {}) ⇒ Object



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
# File 'lib/mongoid_ext/file.rb', line 13

def put(filename, io, options = {})
  mark_parent!

  options[:_id] = grid_filename

  options[:metadata] ||= {}
  options[:metadata][:collection] = _root_document.collection.name

  self["name"] = filename
  if filename =~ /\.([\w]{2,4})$/
    self["extension"] = $1
  end

  if io.kind_of?(String)
    io = StringIO.new(io)
  end

  if defined?(Magic) && Magic.respond_to?(:guess_string_mime_type)
    data = io.read(256) # be nice with memory usage
    self["content_type"] = options[:content_type] = Magic.guess_string_mime_type(data.to_s)

    if self.fetch("extension", nil).nil?
      self["extension"] = options[:content_type].to_s.split("/").last.split("-").last
    end

    if io.respond_to?(:rewind)
      io.rewind
    else
      io.seek(0)
    end
  end

  options[:filename] = grid_filename
  gridfs.delete(grid_filename)
  gridfs.put(io, options)

  if file = self.get
    self['md5'] = file.md5
  end
end