lib/moneta/adapters/mongo/base.rb in moneta-0.8.0 vs lib/moneta/adapters/mongo/base.rb in moneta-0.8.1

- old
+ new

@@ -1,5 +1,7 @@ +require 'bson' + module Moneta module Adapters # @api private class MongoBase include Defaults @@ -28,11 +30,16 @@ doc.delete(@expires_field) doc when 'Number' doc[@value_field] else - doc[@value_field].to_s + # In ruby_bson version 2 (and probably up), #to_s no longer returns the binary data + if doc[@value_field].is_a? ::BSON::Binary and defined? ::BSON::VERSION and ::BSON::VERSION[0].to_i >= 2 + doc[@value_field].data + else + doc[@value_field].to_s + end end end def value_to_doc(key, value, options) case value @@ -55,9 +62,17 @@ # @expires_field must be a Time object (BSON date datatype) @expires_field => expires_at(options) || nil } else raise ArgumentError, "Invalid value type: #{value.class}" end + end + + # BSON will use String#force_encoding to make the string 8-bit + # ASCII. This could break unicode text so we should dup in this + # case, and it also fails with frozen strings. + def to_binary(s) + s = s.dup if s.frozen? || s.encoding != Encoding::ASCII_8BIT + ::BSON::Binary.new(s) end end end end