Sha256: a6e12d8778ad753fbc57d62559f332e281fa156b8983ff5f0edc79549d9f7d5c

Contents?: true

Size: 1.67 KB

Versions: 5

Compression:

Stored size: 1.67 KB

Contents

module MongoMapperExt
  class File
    include MongoMapper::EmbeddedDocument

    key :_id, String
    key :name, String
    key :extension, String
    key :content_type, String

    alias :filename :name

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

      gridfs.delete(grid_filename)
      gridfs.put(io, grid_filename, options).inspect
    end

    def get
      gridfs.get(grid_filename)
    end

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

    def mime_type
      self.content_type || get.content_type
    end

    def size
      get.file_length
    end

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

    def delete
      gridfs.delete(grid_filename)
    end

    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

    protected
    def gridfs
      _root_document.class.gridfs
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mongomapper_ext-0.2.4 lib/mongomapper_ext/file.rb
mongomapper_ext-0.2.3 lib/mongomapper_ext/file.rb
mongomapper_ext-0.2.2 lib/mongomapper_ext/file.rb
mongomapper_ext-0.2.1 lib/mongomapper_ext/file.rb
mongomapper_ext-0.2.0 lib/mongomapper_ext/file.rb