Module: BSONMiniHash

Defined in:
lib/bson_minihash.rb,
lib/bson_minihash/hex.rb,
lib/bson_minihash/version.rb

Defined Under Namespace

Modules: Hex

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.bson_libObject



3
4
5
6
7
8
9
10
11
12
# File 'lib/bson_minihash.rb', line 3

def self.bson_lib
  case
    when Kernel.const_defined?(:Moped) # Mongoid
      :moped
    when Kernel.const_defined?(:BSON) # Mongo driver (incliding MongoMapper)
      :bson
    else 
      raise "In order to use BSONMiniHash, you need to have either the 'bson' or 'moped' gem loaded"
  end
end

.digest(data, type) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bson_minihash.rb', line 33

def self.digest(data, type)
  packed_str = \
    case
      when Hex::TYPES.include?(type)
        Hex.digest(data, type)
      else
        raise ArgumentError, "type #{type} not supported"
    end

  bson_obj(packed_str)
end

.pack(str, type = :hex) ⇒ Object

Beware, if you’re not using SHA1, MD5 or any other hash with a length divisible by two, you’ll get a zero padded string when doing a round trip as the packed string will have an extra nibble of space at the end.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/bson_minihash.rb', line 19

def self.pack(str, type = :hex)
  str = str.downcase.strip

  packed_str = \
    case
      when Hex::TYPES.include?(type)
        Hex.pack(str, type)
      else
        raise ArgumentError, "type #{type} not supported"
    end

  bson_obj(packed_str)
end

.unpack(packed_obj, type = :hex) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bson_minihash.rb', line 45

def self.unpack(packed_obj, type = :hex)
  #
  # Both BSON and Moped give the right thing for to_s
  #
  packed_str = packed_obj.to_s

  case
    when Hex::TYPES.include?(type)
      Hex.unpack(packed_str)
    else
      raise ArgumentError, "type #{type} not supported"
  end
end