Class: MongoMapperExt::File

Inherits:
Object
  • Object
show all
Includes:
MongoMapper::EmbeddedDocument
Defined in:
lib/mongomapper_ext/file.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/mongomapper_ext/file.rb', line 73

def method_missing(name, *args, &block)
  f = self.get rescue nil
  if f && f.respond_to?(name)
    f.send(name, *args, &block)
  else
    super(name, *args, &block)
  end
end

Instance Method Details

#deleteObject



68
69
70
71
# File 'lib/mongomapper_ext/file.rb', line 68

def delete
  @io = nil
  gridfs.delete(grid_filename)
end

#getObject



44
45
46
# File 'lib/mongomapper_ext/file.rb', line 44

def get
  @io ||= gridfs.get(grid_filename)
end

#grid_filenameObject



52
53
54
# File 'lib/mongomapper_ext/file.rb', line 52

def grid_filename
  @grid_filename ||= "#{_root_document.collection.name}/#{self.id}"
end

#mime_typeObject



56
57
58
# File 'lib/mongomapper_ext/file.rb', line 56

def mime_type
  self.content_type || get.content_type
end

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



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

def put(filename, io, options = {})
  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)
    self.extension ||= options[:content_type].to_s.split("/").last.split("-").last

    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)
end

#read(size = nil) ⇒ Object



64
65
66
# File 'lib/mongomapper_ext/file.rb', line 64

def read(size = nil)
  self.get.read(size)
end

#resetObject



48
49
50
# File 'lib/mongomapper_ext/file.rb', line 48

def reset
  @io = nil
end

#sizeObject



60
61
62
# File 'lib/mongomapper_ext/file.rb', line 60

def size
  get.file_length
end