Class: GridFS::Chunk

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo/gridfs/chunk.rb

Overview

A chunk stores a portion of GridStore data.

Constant Summary collapse

DEFAULT_CHUNK_SIZE =
1024 * 256

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, mongo_object = {}) ⇒ Chunk

Returns a new instance of Chunk.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/mongo/gridfs/chunk.rb', line 32

def initialize(file, mongo_object={})
  @file = file
  @object_id = mongo_object['_id'] || Mongo::ObjectID.new
  @chunk_number = mongo_object['n'] || 0

  @data = ByteBuffer.new
  case mongo_object['data']
  when String
    mongo_object['data'].each_byte { |b| @data.put(b) }
  when ByteBuffer
    @data.put_array(mongo_object['data'].to_a)
  when Array
    @data.put_array(mongo_object['data'])
  when nil
  else
    raise "illegal chunk format; data is #{mongo_object['data'] ? (' ' + mongo_object['data'].class.name) : 'nil'}"
  end
  @data.rewind
end

Instance Attribute Details

#chunk_numberObject (readonly)

Returns the value of attribute chunk_number.



29
30
31
# File 'lib/mongo/gridfs/chunk.rb', line 29

def chunk_number
  @chunk_number
end

#dataObject

Returns the value of attribute data.



30
31
32
# File 'lib/mongo/gridfs/chunk.rb', line 30

def data
  @data
end

#object_idObject (readonly)

Returns the value of attribute object_id.



29
30
31
# File 'lib/mongo/gridfs/chunk.rb', line 29

def object_id
  @object_id
end

Instance Method Details

#eof?Boolean

Returns:

  • (Boolean)


54
# File 'lib/mongo/gridfs/chunk.rb', line 54

def eof?; !@data.more?; end

#getcObject



68
69
70
# File 'lib/mongo/gridfs/chunk.rb', line 68

def getc
  @data.more? ? @data.get : nil
end

#posObject



52
# File 'lib/mongo/gridfs/chunk.rb', line 52

def pos; @data.position; end

#pos=(pos) ⇒ Object



53
# File 'lib/mongo/gridfs/chunk.rb', line 53

def pos=(pos); @data.position = pos; end

#putc(byte) ⇒ Object



72
73
74
# File 'lib/mongo/gridfs/chunk.rb', line 72

def putc(byte)
  @data.put(byte)
end

#saveObject



76
77
78
79
80
# File 'lib/mongo/gridfs/chunk.rb', line 76

def save
  coll = @file.chunk_collection
  coll.remove({'_id' => @object_id})
  coll.insert(to_mongo_object)
end

#sizeObject Also known as: length



56
# File 'lib/mongo/gridfs/chunk.rb', line 56

def size; @data.size; end

#to_mongo_objectObject



82
83
84
85
86
87
88
89
# File 'lib/mongo/gridfs/chunk.rb', line 82

def to_mongo_object
  h = OrderedHash.new
  h['_id'] = @object_id
  h['files_id'] = @file.files_id
  h['n'] = @chunk_number
  h['data'] = data
  h
end

#truncateObject

Erase all data after current position.



60
61
62
63
64
65
66
# File 'lib/mongo/gridfs/chunk.rb', line 60

def truncate
  if @data.position < @data.length
    curr_data = @data
    @data = ByteBuffer.new
    @data.put_array(curr_data.to_a[0...curr_data.position])
  end
end