Skip to content

Commit 6041cd6

Browse files
authored
RUBY-2043 Document binary encoding on Binary objects in tutorial (#151)
1 parent 0976970 commit 6041cd6

File tree

1 file changed

+43
-5
lines changed

1 file changed

+43
-5
lines changed

docs/tutorials/bson-v4.txt

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,15 +232,53 @@ specific to the specification:
232232
``BSON::Binary``
233233
````````````````
234234

235-
This is a representation of binary data. The raw data and the subtype must be
236-
provided when constructing.
235+
Use ``BSON::Binary`` objects to store arbitrary binary data. The ``Binary``
236+
objects can be constructed from binary strings as follows:
237237

238238
.. code-block:: ruby
239239

240-
BSON::Binary.new(binary_data, :md5)
240+
BSON::Binary.new("binary_string")
241+
# => <BSON::Binary:0x47113101192900 type=generic data=0x62696e6172795f73...>
241242

242-
Valid subtypes are: ``:generic``, ``:function``, ``:old``, ``:uuid_old``,
243-
``:uuid``, ``:md5``, ``:user``.
243+
By default, ``Binary`` objects are created with BSON binary subtype 0
244+
(``:generic``). The subtype can be explicitly specified to indicate that
245+
the bytes encode a particular type of data:
246+
247+
.. code-block:: ruby
248+
249+
BSON::Binary.new("binary_string", :user)
250+
# => <BSON::Binary:0x47113101225420 type=user data=0x62696e6172795f73...>
251+
252+
Valid subtypes are ``:generic``, ``:function``, ``:old``, ``:uuid_old``,
253+
``:uuid``, ``:md5`` and ``:user``.
254+
255+
The data and the subtype can be retrieved from ``Binary`` instances using
256+
``data`` and ``type`` attributes, as follows:
257+
258+
.. code-block:: ruby
259+
260+
binary = BSON::Binary.new("binary_string", :user)
261+
binary.data
262+
=> "binary_string"
263+
binary.type
264+
=> :user
265+
266+
.. note::
267+
268+
``BSON::Binary`` objects always store the data in ``BINARY`` encoding,
269+
regardless of the encoding that the string passed to the constructor
270+
was in:
271+
272+
.. code-block:: ruby
273+
274+
str = "binary_string"
275+
str.encoding
276+
# => #<Encoding:US-ASCII>
277+
binary = BSON::Binary.new(str)
278+
binary.data
279+
# => "binary_string"
280+
binary.data.encoding
281+
# => #<Encoding:ASCII-8BIT>
244282

245283
UUID Methods
246284
~~~~~~~~~~~~

0 commit comments

Comments
 (0)