Class: Moped::BSON::ObjectId

Inherits:
Object
  • Object
show all
Defined in:
lib/moped/bson/object_id.rb

Defined Under Namespace

Classes: Generator

Constant Summary collapse

@@string_format =

Formatting string for outputting an ObjectId.

("%02x" * 12).freeze
@@generator =
Generator.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.__bson_load__(io) ⇒ Object



67
68
69
# File 'lib/moped/bson/object_id.rb', line 67

def __bson_load__(io)
  from_data(io.read(12))
end

.from_data(data) ⇒ Object



27
28
29
30
31
# File 'lib/moped/bson/object_id.rb', line 27

def from_data(data)
  id = allocate
  id.send(:data=, data)
  id
end

.from_string(string) ⇒ Object



12
13
14
15
16
17
# File 'lib/moped/bson/object_id.rb', line 12

def from_string(string)
  raise Errors::InvalidObjectId.new(string) unless legal?(string)
  data = []
  12.times { |i| data << string[i*2, 2].to_i(16) }
  from_data data.pack("C12")
end

.from_time(time) ⇒ Object



19
20
21
# File 'lib/moped/bson/object_id.rb', line 19

def from_time(time)
  from_data @@generator.generate(time.to_i)
end

.legal?(str) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/moped/bson/object_id.rb', line 23

def legal?(str)
  !!str.match(/\A\h{24}\Z/i)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



42
43
44
# File 'lib/moped/bson/object_id.rb', line 42

def ==(other)
  BSON::ObjectId === other && data == other.data
end

#__bson_dump__(io, key) ⇒ Object



72
73
74
75
76
# File 'lib/moped/bson/object_id.rb', line 72

def __bson_dump__(io, key)
  io << Types::OBJECT_ID
  io << key.to_bson_cstring
  io << data
end

#dataObject



34
35
36
37
38
39
40
# File 'lib/moped/bson/object_id.rb', line 34

def data
  # If @data is defined, then we know we've been loaded in some
  # non-standard way, so we attempt to repair the data.
  repair! @data if defined? @data

  @raw_data ||= @@generator.next
end

#generation_timeObject

Return the UTC time at which this ObjectId was generated. This may be used instread of a created_at timestamp since this information is always encoded in the object id.



62
63
64
# File 'lib/moped/bson/object_id.rb', line 62

def generation_time
  Time.at(data.unpack("N")[0]).utc
end

#hashObject



47
48
49
# File 'lib/moped/bson/object_id.rb', line 47

def hash
  data.hash
end

#marshal_dumpObject



111
112
113
# File 'lib/moped/bson/object_id.rb', line 111

def marshal_dump
  data
end

#marshal_load(data) ⇒ Object



116
117
118
# File 'lib/moped/bson/object_id.rb', line 116

def marshal_load(data)
  self.data = data
end

#to_json(*args) ⇒ Object



55
56
57
# File 'lib/moped/bson/object_id.rb', line 55

def to_json(*args)
  "{\"$oid\": \"#{to_s}\"}"
end

#to_sObject



51
52
53
# File 'lib/moped/bson/object_id.rb', line 51

def to_s
  @@string_format % data.unpack("C12")
end