@@ -14,12 +14,12 @@ BSON 4.x Tutorial
14
14
:depth: 1
15
15
:class: twocols
16
16
17
- This tutorial discusses using the core Ruby BSON gem .
17
+ This tutorial discusses using the Ruby BSON library .
18
18
19
19
Installation
20
20
------------
21
21
22
- The BSON gem is hosted on `Rubygems <http://rubygems.org>`_ and can be installed
22
+ The BSON library can be installed from `Rubygems <http://rubygems.org>`_
23
23
manually or with bundler.
24
24
25
25
To install the gem manually:
@@ -28,13 +28,13 @@ To install the gem manually:
28
28
29
29
gem install bson -v '~> 4.0'
30
30
31
- To install the gem with bundler, include the following in your Gemfile:
31
+ To install the gem with bundler, include the following in your `` Gemfile`` :
32
32
33
33
.. code-block:: ruby
34
34
35
35
gem 'bson', '~> 4.0'
36
36
37
- The BSON gem is compatible with MRI >= 2.3 and JRuby >= 9.2.
37
+ The BSON library is compatible with MRI >= 2.3 and JRuby >= 9.2.
38
38
39
39
Use With ActiveSupport
40
40
----------------------
@@ -469,6 +469,53 @@ decimal rounding with exact precision.
469
469
d = BigDecimal(1.28, 3)
470
470
BSON::Decimal128.new(d)
471
471
472
+ ``Symbol``
473
+ ``````````
474
+
475
+ The BSON specification defines a symbol type which allows round-tripping
476
+ Ruby ``Symbol`` values (i.e., a Ruby ``Symbol``is encoded into a BSON symbol
477
+ and a BSON symbol is decoded into a Ruby ``Symbol``). However, since most
478
+ programming langauges do not have a native symbol type, to promote
479
+ interoperabilty, MongoDB deprecated the BSON symbol type and encourages
480
+ strings to be used instead.
481
+
482
+ .. note::
483
+
484
+ In BSON, hash *keys* are always strings. Non-string values will be
485
+ stringified when used as hash keys:
486
+
487
+ .. code-block:: ruby
488
+
489
+ Hash.from_bson({foo: 'bar'}.to_bson)
490
+ # => {"foo"=>"bar"}
491
+
492
+ Hash.from_bson({1 => 2}.to_bson)
493
+ # => {"1"=>2}
494
+
495
+ By default, the BSON library encodes ``Symbol`` hash values as strings and
496
+ decodes BSON symbols into Ruby ``Symbol`` values:
497
+
498
+ .. code-block:: ruby
499
+
500
+ {foo: :bar}.to_bson.to_s
501
+ # => "\x12\x00\x00\x00\x02foo\x00\x04\x00\x00\x00bar\x00\x00"
502
+
503
+ # 0x02 is the string type
504
+ Hash.from_bson(BSON::ByteBuffer.new("\x12\x00\x00\x00\x02foo\x00\x04\x00\x00\x00bar\x00\x00".force_encoding('BINARY')))
505
+ # => {"foo"=>"bar"}
506
+
507
+ # 0x0E is the symbol type
508
+ Hash.from_bson(BSON::ByteBuffer.new("\x12\x00\x00\x00\x0Efoo\x00\x04\x00\x00\x00bar\x00\x00".force_encoding('BINARY')))
509
+ # => {"foo"=>:bar}
510
+
511
+ To force encoding of Ruby symbols to BSON symbols, wrap the Ruby symbols in
512
+ ``BSON::Symbol::Raw``:
513
+
514
+ .. code-block:: ruby
515
+
516
+ {foo: BSON::Symbol::Raw.new(:bar)}.to_bson.to_s
517
+ # => "\x12\x00\x00\x00\x0Efoo\x00\x04\x00\x00\x00bar\x00\x00"
518
+
472
519
JSON Serialization
473
520
------------------
474
521
0 commit comments