Class: GridFS::Chunk

Inherits:
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.



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

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.



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

def chunk_number
  @chunk_number
end

#dataObject

Returns the value of attribute data.



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

def data
  @data
end

#object_idObject (readonly)

Returns the value of attribute object_id.



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

def object_id
  @object_id
end

Instance Method Details

#eof?Boolean

Returns:

  • (Boolean)


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

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

#getcObject



66
67
68
# File 'lib/mongo/gridfs/chunk.rb', line 66

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

#posObject



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

def pos; @data.position; end

#pos=(pos) ⇒ Object



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

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

#putc(byte) ⇒ Object



70
71
72
# File 'lib/mongo/gridfs/chunk.rb', line 70

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

#saveObject



74
75
76
77
78
# File 'lib/mongo/gridfs/chunk.rb', line 74

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

#sizeObject Also known as: length



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

def size; @data.size; end

#to_mongo_objectObject



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

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



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

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