oj 3.7.4 → 3.13.21

Sign up to get free protection for your applications and to get access to all the features.
Files changed (142) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1352 -0
  3. data/README.md +29 -8
  4. data/RELEASE_NOTES.md +61 -0
  5. data/ext/oj/buf.h +53 -72
  6. data/ext/oj/cache.c +326 -0
  7. data/ext/oj/cache.h +21 -0
  8. data/ext/oj/cache8.c +61 -64
  9. data/ext/oj/cache8.h +12 -39
  10. data/ext/oj/circarray.c +37 -43
  11. data/ext/oj/circarray.h +16 -17
  12. data/ext/oj/code.c +165 -179
  13. data/ext/oj/code.h +27 -29
  14. data/ext/oj/compat.c +174 -194
  15. data/ext/oj/custom.c +809 -866
  16. data/ext/oj/debug.c +132 -0
  17. data/ext/oj/dump.c +848 -863
  18. data/ext/oj/dump.h +81 -67
  19. data/ext/oj/dump_compat.c +85 -123
  20. data/ext/oj/dump_leaf.c +100 -188
  21. data/ext/oj/dump_object.c +527 -656
  22. data/ext/oj/dump_strict.c +315 -338
  23. data/ext/oj/encode.h +7 -34
  24. data/ext/oj/encoder.c +43 -0
  25. data/ext/oj/err.c +40 -29
  26. data/ext/oj/err.h +48 -48
  27. data/ext/oj/extconf.rb +17 -4
  28. data/ext/oj/fast.c +1070 -1087
  29. data/ext/oj/intern.c +301 -0
  30. data/ext/oj/intern.h +26 -0
  31. data/ext/oj/mimic_json.c +469 -436
  32. data/ext/oj/object.c +525 -593
  33. data/ext/oj/odd.c +154 -138
  34. data/ext/oj/odd.h +37 -38
  35. data/ext/oj/oj.c +1325 -986
  36. data/ext/oj/oj.h +333 -316
  37. data/ext/oj/parse.c +1002 -846
  38. data/ext/oj/parse.h +92 -87
  39. data/ext/oj/parser.c +1557 -0
  40. data/ext/oj/parser.h +91 -0
  41. data/ext/oj/rails.c +888 -878
  42. data/ext/oj/rails.h +11 -14
  43. data/ext/oj/reader.c +141 -147
  44. data/ext/oj/reader.h +73 -89
  45. data/ext/oj/resolve.c +41 -62
  46. data/ext/oj/resolve.h +7 -9
  47. data/ext/oj/rxclass.c +71 -75
  48. data/ext/oj/rxclass.h +18 -19
  49. data/ext/oj/saj.c +443 -486
  50. data/ext/oj/saj2.c +602 -0
  51. data/ext/oj/scp.c +88 -113
  52. data/ext/oj/sparse.c +787 -709
  53. data/ext/oj/stream_writer.c +133 -159
  54. data/ext/oj/strict.c +127 -118
  55. data/ext/oj/string_writer.c +230 -249
  56. data/ext/oj/trace.c +34 -41
  57. data/ext/oj/trace.h +19 -19
  58. data/ext/oj/usual.c +1254 -0
  59. data/ext/oj/util.c +136 -0
  60. data/ext/oj/util.h +20 -0
  61. data/ext/oj/val_stack.c +59 -67
  62. data/ext/oj/val_stack.h +91 -129
  63. data/ext/oj/validate.c +46 -0
  64. data/ext/oj/wab.c +342 -353
  65. data/lib/oj/bag.rb +1 -0
  66. data/lib/oj/easy_hash.rb +5 -4
  67. data/lib/oj/error.rb +1 -1
  68. data/lib/oj/json.rb +1 -1
  69. data/lib/oj/mimic.rb +48 -14
  70. data/lib/oj/saj.rb +20 -6
  71. data/lib/oj/state.rb +8 -7
  72. data/lib/oj/version.rb +2 -2
  73. data/lib/oj.rb +0 -8
  74. data/pages/Compatibility.md +1 -1
  75. data/pages/JsonGem.md +15 -0
  76. data/pages/Modes.md +53 -46
  77. data/pages/Options.md +72 -11
  78. data/pages/Parser.md +309 -0
  79. data/pages/Rails.md +73 -22
  80. data/pages/Security.md +1 -1
  81. data/test/activerecord/result_test.rb +7 -2
  82. data/test/activesupport5/abstract_unit.rb +45 -0
  83. data/test/activesupport5/decoding_test.rb +68 -60
  84. data/test/activesupport5/encoding_test.rb +111 -96
  85. data/test/activesupport5/encoding_test_cases.rb +33 -25
  86. data/test/activesupport5/test_helper.rb +43 -21
  87. data/test/activesupport5/time_zone_test_helpers.rb +18 -3
  88. data/test/activesupport6/abstract_unit.rb +44 -0
  89. data/test/activesupport6/decoding_test.rb +133 -0
  90. data/test/activesupport6/encoding_test.rb +507 -0
  91. data/test/activesupport6/encoding_test_cases.rb +98 -0
  92. data/test/activesupport6/test_common.rb +17 -0
  93. data/test/activesupport6/test_helper.rb +163 -0
  94. data/test/activesupport6/time_zone_test_helpers.rb +39 -0
  95. data/test/activesupport7/abstract_unit.rb +49 -0
  96. data/test/activesupport7/decoding_test.rb +125 -0
  97. data/test/activesupport7/encoding_test.rb +486 -0
  98. data/test/activesupport7/encoding_test_cases.rb +104 -0
  99. data/test/activesupport7/time_zone_test_helpers.rb +47 -0
  100. data/test/bar.rb +6 -12
  101. data/test/baz.rb +16 -0
  102. data/test/bug.rb +16 -0
  103. data/test/foo.rb +69 -75
  104. data/test/helper.rb +16 -0
  105. data/test/json_gem/json_common_interface_test.rb +8 -3
  106. data/test/json_gem/json_generator_test.rb +18 -4
  107. data/test/json_gem/json_parser_test.rb +9 -0
  108. data/test/json_gem/test_helper.rb +12 -0
  109. data/test/mem.rb +33 -0
  110. data/test/perf.rb +1 -1
  111. data/test/perf_dump.rb +50 -0
  112. data/test/perf_once.rb +58 -0
  113. data/test/perf_parser.rb +189 -0
  114. data/test/perf_scp.rb +11 -10
  115. data/test/perf_strict.rb +17 -23
  116. data/test/prec.rb +23 -0
  117. data/test/sample_json.rb +1 -1
  118. data/test/test_compat.rb +46 -10
  119. data/test/test_custom.rb +147 -8
  120. data/test/test_fast.rb +62 -2
  121. data/test/test_file.rb +25 -2
  122. data/test/test_gc.rb +13 -0
  123. data/test/test_generate.rb +21 -0
  124. data/test/test_hash.rb +11 -1
  125. data/test/test_integer_range.rb +7 -2
  126. data/test/test_object.rb +85 -9
  127. data/test/test_parser.rb +27 -0
  128. data/test/test_parser_saj.rb +335 -0
  129. data/test/test_parser_usual.rb +217 -0
  130. data/test/test_rails.rb +35 -0
  131. data/test/test_saj.rb +1 -1
  132. data/test/test_scp.rb +5 -5
  133. data/test/test_strict.rb +26 -1
  134. data/test/test_various.rb +87 -65
  135. data/test/test_wab.rb +2 -0
  136. data/test/test_writer.rb +19 -2
  137. data/test/tests.rb +1 -1
  138. data/test/zoo.rb +13 -0
  139. metadata +60 -110
  140. data/ext/oj/hash.c +0 -163
  141. data/ext/oj/hash.h +0 -46
  142. data/ext/oj/hash_test.c +0 -512
data/pages/Parser.md ADDED
@@ -0,0 +1,309 @@
1
+ # How Oj Just Got Faster
2
+
3
+ The original Oj parser is a performant parser that supports several
4
+ modes. As of this writing Oj is almost 10 years old. A dinosaur by
5
+ coding standards. It was time for an upgrade. Dealing with issues over
6
+ the years it became clear that a few things could have been done
7
+ better. The new `Oj::Parser` is a response that not only attempts to
8
+ address some of the issues but also give the Oj parser a significant
9
+ boost in performance. `Oj::Parser` takes a different approach to JSON
10
+ parsing than the now legacy Oj parser. Not really a legacy parser yet
11
+ since the `Oj::Parser` is not a drop-in replacement for the JSON gem
12
+ but it is as much 3 times or more faster than the previous parser in
13
+ some modes.
14
+
15
+ ## Address Issues
16
+
17
+ There are a few features of the`Oj.load` parser that continue to be
18
+ the reason for many of the issue on the project. The most significant
19
+ area is compatibility with both Rails and the JSON gem as they battle
20
+ it out for which behavior will win out in any particular
21
+ situation. Most of the issues are on the writing or dumping side of
22
+ the JSON packages but some are present on the parsing as
23
+ well. Conversion of decimals is one area where the Rails and the JSON
24
+ gem vary. The `Oj::Parser` addresses this by allowing for completely
25
+ separate parser instances. Create a parser and configure it for the
26
+ situation and leave the others parsers on their own.
27
+
28
+ The `Oj::Parser` is mostly compatible with the JSON gem and Rails but
29
+ no claims are made that the behavior will be the same as either.
30
+
31
+ The most frequent issues that can addressed with the new parser are
32
+ around the handling of options. For `Oj.load` there is a set of
33
+ default options that can be set and the same options can be specified
34
+ for each call to parse or load. This approach as a couple of
35
+ downsides. One the defaults are shared across all calls to parse no
36
+ matter what the desire mode is. The second is that having to provide
37
+ all the options on each parse call incurs a performance penalty and is
38
+ just annoying to repeat the same set of options over may calls.
39
+
40
+ By localizing options to a specific parser instance there is never any
41
+ bleed over to other instances.
42
+
43
+ ## How
44
+
45
+ It's wonderful to wish for a faster parser that solves all the
46
+ annoyances of the previous parser but how was it done is a much more
47
+ interesting question to answer.
48
+
49
+ At the core, the API for parsing was changed. Instead of a sinle
50
+ global parser any number of parsers can be created and each is separate
51
+ from the others. The parser itself is able to rip through a JSON
52
+ string, stream, or file and then make calls to a delegate to process
53
+ the JSON elements according to the delegate behavior. This is similar
54
+ to the `Oj.load` parser but the new parser takes advantage of
55
+ character maps, reduced conditional branching, and calling function
56
+ pointers.
57
+
58
+ ### Options
59
+
60
+ As mentioned, one way to change the options issues was to change the
61
+ API. Instead of having a shared set of default options a separate
62
+ parser is created and configured for each use case. Options are set
63
+ with methods on the parser so no more guessing what options are
64
+ available. With options isolated to individual parsers there is no
65
+ unintended leakage to other parse use cases.
66
+
67
+ ### Structure
68
+
69
+ A relative small amount of time is spent in the actual parsing of JSON
70
+ in `Oj.load`. Most of the time is spent building the Ruby
71
+ Objects. Even cutting the parsing time in half only gives a 10%
72
+ improvement in performance but 10% is still an improvement.
73
+
74
+ The `Oj::Parser` is designed to reduce conditional branching. To do
75
+ that it uses character maps for the various states that the parser
76
+ goes through when parsing. There is no recursion as the JSON elements
77
+ are parsed. The use of a character maps for each parser state means
78
+ the parser function can and is re-entrant so partial blocks of JSON
79
+ can be parsed and the results combined.
80
+
81
+ There are no Ruby calls in the parser itself. Instead delegates are
82
+ used to implement the various behaviors of the parser which are
83
+ currently validation (validate), callbacks (SAJ), or building Ruby
84
+ objects (usual). The delegates are where all the Ruby calls and
85
+ related optimizations take place.
86
+
87
+ Considering JSON file parsing, `Oj.load_file` is able to read a file a
88
+ block at a time and the new `Oj::Parser` does the same. There was a
89
+ change in how that is done though. `Oj.load_file` sets up a reader
90
+ that must be called for each character. Basically a buffered
91
+ reader. `Oj::Parser` drops down a level and uses a re-entrant parser
92
+ that takes a block of bytes at a time so there is no call needed for
93
+ each character but rather just iterating over the block read from the
94
+ file.
95
+
96
+ Reading a block at a time also allows for an efficient second thread
97
+ to be used for reading blocks. That feature is not in the first
98
+ iteration of the `Oj::Parser` but the stage is set for it in the
99
+ future. The same approach was used successfully in
100
+ [OjC](https://github.com/ohler55/ojc) which is where the code for the
101
+ parser was taken from.
102
+
103
+ ### Delegates
104
+
105
+ There are three delegates; validate, SAJ, and usual.
106
+
107
+ #### Validate
108
+
109
+ The validate delegate is trivial in that does nothing other than let
110
+ the parser complete. There are no options for the validate
111
+ delegate. By not making any Ruby calls other than to start the parsing
112
+ the validate delegate is no surprise that the validate delegate is the
113
+ best performer.
114
+
115
+ #### SAJ (Simple API for JSON)
116
+
117
+ The SAJ delegate is compatible with the SAJ handlers used with
118
+ `Oj.saj_parse` so it needs to keep track of keys for the
119
+ callbacks. Two optimizations are used. The first is a reuseable key
120
+ stack while the second is a string cache similar to the Ruby intern
121
+ function.
122
+
123
+ When parsing a Hash (JSON object) element the key is passed to the
124
+ callback function if the SAJ handler responds to the method. The key
125
+ is also provided when closing an Array or Hash that is part of a
126
+ parent Hash. A key stack supports this.
127
+
128
+ If the option is turned on a lookup is made and previously cached key
129
+ VALUEs are used. This avoids creating the string for the key and
130
+ setting the encoding on it. The cache used is a auto expanding hash
131
+ implementation that is limited to strings less than 35 characters
132
+ which covers most keys. Larger strings use the slower string creation
133
+ approach. The use of the cache reduces object creation which save on
134
+ both memory allocation and time. It is not appropriate for one time
135
+ parsing of say all the keys in a dictionary but is ideally suited for
136
+ loading similar JSON multiple times.
137
+
138
+ #### Usual
139
+
140
+ By far the more complex of the delegates is the 'usual' delegate. The
141
+ usual delegate builds Ruby Objects when parsing JSON. It incorporates
142
+ many options for configuration and makes use of a number of
143
+ optimizations.
144
+
145
+ ##### Reduce Branching
146
+
147
+ In keeping with the goal of reducing conditional branching most of the
148
+ delegate options are implemented by changing a function pointer
149
+ according to the option selected. For example when turning on or off
150
+ `:symbol_keys` the function to calculate the key is changed so no
151
+ decision needs to be made during parsing. Using this approach option
152
+ branching happens when the option is set and not each time when
153
+ parsing.
154
+
155
+ ##### Cache
156
+
157
+ Creating Ruby Objects whether Strings, Array, or some other class is
158
+ expensive. Well expensive when running at the speeds Oj runs at. One
159
+ way to reduce Object creation is to cache those objects on the
160
+ assumption that they will most likely be used again. This is
161
+ especially true of Hash keys and Object attribute IDs. When creating
162
+ Objects from a class name in the JSON a class cache saves resolving
163
+ the string to a class each time. Of course there are times when
164
+ caching is not preferred so caching can be turned on or off with
165
+ option methods on the parser which are passed down to the delegate..
166
+
167
+ The Oj cache implementation is an auto expanding hash. When certain
168
+ limits are reached the hash is expanded and rehashed. Rehashing can
169
+ take some time as the number of items cached increases so there is
170
+ also an option to start with a larger cache size to avoid or reduce
171
+ the likelihood of a rehash.
172
+
173
+ The Oj cache has an advantage over the Ruby intern function
174
+ (`rb_intern()`) in that several steps are needed for some cached
175
+ items. As an example Object attribute IDs are created by adding an `@`
176
+ character prefix to a string and then converting to a ID. This is done
177
+ once when inserting into the cache and after that only a lookup is
178
+ needed.
179
+
180
+ ##### Bulk Insert
181
+
182
+ The Ruby functions available for C extension functions are extensive
183
+ and offer many options across the board. The bulk insert functions for
184
+ both Arrays and Hashes are much faster than appending or setting
185
+ functions that set one value at a time. The Array bulk insert is
186
+ around 15 times faster and for Hash it is about 3 times faster.
187
+
188
+ To take advantage of the bulk inserts arrays of VALUEs are
189
+ needed. With a little planning there VALUE arrays can be reused which
190
+ leads into another optimization, the use of stacks.
191
+
192
+ ##### Stacks
193
+
194
+ Parsing requires memory to keep track of values when parsing nested
195
+ JSON elements. That can be done on the call stack making use of
196
+ recursive calls or it can be done with a stack managed by the
197
+ parser. The `Oj.load` method maintains a stack for Ruby object and
198
+ builds the output as the parsing progresses.
199
+
200
+ `Oj::Parser` uses three different stacks. One stack for values, one
201
+ for keys, and one for collections (Array and Hash). By postponing the
202
+ creation of the collection elements the bulk insertions for Array and
203
+ Hash can be used. For arrays the use of a value stack and creating the
204
+ array after all elements have been identified gives a 15x improvement
205
+ in array creation.
206
+
207
+ For Hash the story is a little different. The bulk insert for Hash
208
+ alternates keys and values but there is a wrinkle to consider. Since
209
+ Ruby Object creation is triggered by the occurrence of an element that
210
+ matches a creation identifier the creation of a collection is not just
211
+ for Array and Hash but also Object. Setting Object attributes uses an
212
+ ID and not a VALUE. For that reason the keys should not be created as
213
+ String or Symbol types as they would be ignored and the VALUE creation
214
+ wasted when setting Object attributes. Using the bulk insert for Hash
215
+ gives a 3x improvement for that part of the object building.
216
+
217
+ Looking at the Object creation the JSON gem expects a class method of
218
+ `#json_create(arg)`. The single argument is the Hash resulting from
219
+ the parsing assuming that the parser parsed to a Hash first. This is
220
+ less than ideal from a performance perspective so `Oj::Parser`
221
+ provides an option to take that approach or to use the much more
222
+ efficient approach of never creating the Hash but instead creating the
223
+ Object and then setting the attributes directly.
224
+
225
+ To further improve performance and reduce the amount of memory
226
+ allocations and frees the stacks are reused from one call to `#parse`
227
+ to another.
228
+
229
+ ## Results
230
+
231
+ The results are even better than expected. Running the
232
+ [perf_parser.rb](https://github.com/ohler55/oj/blob/develop/test/perf_parser.rb)
233
+ file shows the improvements. There are four comparisons all run on a
234
+ MacBook Pro with Intel processor.
235
+
236
+ ### Validation
237
+
238
+ Without a comparible parser that just validates a JSON document the
239
+ `Oj.saj_parse` callback parser with a nil handler is used for
240
+ comparison to the new `Oj::Parser.new(:validate)`. In that case the
241
+ comparison is:
242
+
243
+ ```
244
+ System time (secs) rate (ops/sec)
245
+ ------------------- ----------- --------------
246
+ Oj::Parser.validate 0.101 494369.136
247
+ Oj::Saj.none 0.205 244122.745
248
+ ```
249
+
250
+ The `Oj::Parser.new(:validate)` is **2.03** times faster!
251
+
252
+ ### Callback
253
+
254
+ Oj has two callback parsers. One is SCP and the other SAJ. Both are
255
+ similar in that a handler is provided that implements methods for
256
+ processing the various element types in a JSON document. Comparing
257
+ `Oj.saj_parse` to `Oj::Parser.new(:saj)` with a all callback methods
258
+ implemented handler gives the following raw results:
259
+
260
+ ```
261
+ System time (secs) rate (ops/sec)
262
+ -------------- ----------- --------------
263
+ Oj::Parser.saj 0.783 63836.986
264
+ Oj::Saj.all 1.182 42315.397
265
+ ```
266
+
267
+ The `Oj::Parser.new(:saj)` is **1.51** times faster.
268
+
269
+ ### Parse to Ruby primitives
270
+
271
+ Parsing to Ruby primitives and Array and Hash is possible with most
272
+ parsers including the JSON gem parser. The raw results comparing
273
+ `Oj.strict_load`, `Oj::Parser.new(:usual)`, and the JSON gem are:
274
+
275
+ ```
276
+ System time (secs) rate (ops/sec)
277
+ ---------------- ----------- --------------
278
+ Oj::Parser.usual 0.452 110544.876
279
+ Oj::strict_load 0.699 71490.257
280
+ JSON::Ext 1.009 49555.094
281
+ ```
282
+
283
+ The `Oj::Parser.new(:saj)` is **1.55** times faster than `Oj.load` and
284
+ **2.23** times faster than the JSON gem.
285
+
286
+ ### Object
287
+
288
+ Oj supports two modes for Object serialization and
289
+ deserialization. Comparing to the JSON gem compatible mode
290
+ `Oj.compat_load`, `Oj::Parser.new(:usual)`, and the JSON gem yields
291
+ the following raw results:
292
+
293
+ ```
294
+ System time (secs) rate (ops/sec)
295
+ ---------------- ----------- --------------
296
+ Oj::Parser.usual 0.071 703502.033
297
+ Oj::compat_load 0.225 221762.927
298
+ JSON::Ext 0.401 124638.859
299
+ ```
300
+
301
+ The `Oj::Parser.new(:saj)` is **3.17** times faster than
302
+ `Oj.compat_load` and **5.64** times faster than the JSON gem.
303
+
304
+ ## Summary
305
+
306
+ With a performance boost of from 1.5x to over 3x over the `Oj.load`
307
+ parser the new `Oj::Parser` is a big win in the performance arena. The
308
+ isolation of options is another feature that should make life easier
309
+ for developers.
data/pages/Rails.md CHANGED
@@ -1,3 +1,15 @@
1
+ # Rails Quickstart
2
+
3
+ To universally replace Rails' use of the json gem with Oj, and also
4
+ have Oj "take over" many methods on the JSON constant (`load`, `parse`, etc.) with
5
+ their faster Oj counterparts, add this to an initializer:
6
+
7
+ ```ruby
8
+ Oj.optimize_rails()
9
+ ```
10
+
11
+ For more details and options, read on...
12
+
1
13
  # Oj Rails Compatibility
2
14
 
3
15
  The `:rails` mode mimics the ActiveSupport version 5 encoder. Rails and
@@ -26,44 +38,44 @@ directly. If Rails mode is also desired then use the `Oj.default_options` to
26
38
  change the default mode.
27
39
 
28
40
  Some of the Oj options are supported as arguments to the encoder if called
29
- from Oj::Rails.encode() but when using the Oj::Rails::Encoder class the
30
- encode() method does not support optional arguments as required by the
41
+ from `Oj::Rails.encode()` but when using the `Oj::Rails::Encoder` class the
42
+ `encode()` method does not support optional arguments as required by the
31
43
  ActiveSupport compliance guidelines. The general approach Rails takes for
32
44
  configuring encoding options is to either set global values or to create a new
33
45
  instance of the Encoder class and provide options in the initializer.
34
46
 
35
47
  The globals that ActiveSupport uses for encoding are:
36
48
 
37
- * ActiveSupport::JSON::Encoding.use_standard_json_time_format
38
- * ActiveSupport::JSON::Encoding.escape_html_entities_in_json
39
- * ActiveSupport::JSON::Encoding.time_precision
40
- * ActiveSupport::JSON::Encoding.json_encoder
49
+ * `ActiveSupport::JSON::Encoding.use_standard_json_time_format`
50
+ * `ActiveSupport::JSON::Encoding.escape_html_entities_in_json`
51
+ * `ActiveSupport::JSON::Encoding.time_precision`
52
+ * `ActiveSupport::JSON::Encoding.json_encoder`
41
53
 
42
54
  Those globals are aliased to also be accessed from the ActiveSupport module
43
- directly so ActiveSupport::JSON::Encoding.time_precision can also be accessed
44
- from ActiveSupport.time_precision. Oj makes use of these globals in mimicing
45
- Rails after the Oj::Rails.set_encode() method is called. That also sets the
46
- ActiveSupport.json_encoder to the Oj::Rails::Encoder class.
55
+ directly so `ActiveSupport::JSON::Encoding.time_precision` can also be accessed
56
+ from `ActiveSupport.time_precision`. Oj makes use of these globals in mimicking
57
+ Rails after the `Oj::Rails.set_encode()` method is called. That also sets the
58
+ `ActiveSupport.json_encoder` to the `Oj::Rails::Encoder` class.
47
59
 
48
- Options passed into a call to to_json() are passed to the as_json()
60
+ Options passed into a call to `to_json()` are passed to the `as_json()`
49
61
  methods. These are mostly ignored by Oj and simply passed on without
50
62
  modifications as per the guidelines. The exception to this are the options
51
- specific to Oj such as the :circular option which it used to detect circular
63
+ specific to Oj such as the `:circular` option which it used to detect circular
52
64
  references while encoding.
53
65
 
54
66
  By default Oj acts like the ActiveSupport encoder and honors any changes in
55
- the as_json() methods. There are some optimized Oj encoders for some
56
- classes. When the optimized encoder it toggled the as_json() methods will not
67
+ the `as_json()` methods. There are some optimized Oj encoders for some
68
+ classes. When the optimized encoder it toggled the `as_json()` methods will not
57
69
  be called for that class but instead the optimized version will be called. The
58
70
  optimized version is the same as the ActiveSupport default encoding for a
59
- given class. The optimized versions are toggled with the optimize() and
60
- deoptimize() methods. There is a default optimized version for every class
71
+ given class. The optimized versions are toggled with the `optimize()` and
72
+ `deoptimize()` methods. There is a default optimized version for every class
61
73
  that takes the visible attributes and encodes them but that may not be the
62
74
  same as what Rails uses. Trial and error is the best approach for classes not
63
75
  listed here.
64
76
 
65
77
  The classes that can be put in optimized mode and are optimized when
66
- Oj::Rails.optimize is called with no arguments are:
78
+ `Oj::Rails.optimize` is called with no arguments are:
67
79
 
68
80
  * Array
69
81
  * BigDecimal
@@ -77,8 +89,47 @@ Oj::Rails.optimize is called with no arguments are:
77
89
  * any class inheriting from ActiveRecord::Base
78
90
  * any other class where all attributes should be dumped
79
91
 
80
- The ActiveSupport decoder is the JSON.parse() method. Calling the
81
- Oj::Rails.set_decoder() method replaces that method with the Oj equivalent.
92
+ The ActiveSupport decoder is the `JSON.parse()` method. Calling the
93
+ `Oj::Rails.set_decoder()` method replaces that method with the Oj equivalent.
94
+
95
+ ### Usage in Rails 3
96
+
97
+ To support Rails 3 you can create a new module mixin to prepend to controllers:
98
+
99
+ ```ruby
100
+ require 'oj'
101
+
102
+ module OjJsonEncoder
103
+ def render(options = nil, extra_options = {}, &block)
104
+ if options && options.is_a?(Hash) && options[:json]
105
+ obj = options.delete(:json)
106
+ obj = Oj.dump(obj, :mode => :rails) unless obj.is_a?(String)
107
+ options[:text] = obj
108
+ response.content_type ||= Mime::JSON
109
+ end
110
+ super
111
+ end
112
+ end
113
+ ```
114
+
115
+ Usage:
116
+
117
+ ```ruby
118
+ class MyController < ApplicationController
119
+ prepend OjJsonEncoder
120
+ def index
121
+ render :json => { :hello => 'world' }
122
+ end
123
+ end
124
+ ```
125
+
126
+ ### Older Ruby Version Support (Pre 2.3.0)
127
+
128
+ If you are using an older version of Ruby, you can pin `oj` to an earlier version in your Gemfile:
129
+
130
+ ```ruby
131
+ gem 'oj', '3.7.12'
132
+ ```
82
133
 
83
134
  ### Notes:
84
135
 
@@ -86,9 +137,9 @@ Oj::Rails.set_decoder() method replaces that method with the Oj equivalent.
86
137
  Ruby which is used by the json gem and by Rails. Ruby varies the
87
138
  significant digits which can be either 16 or 17 depending on the value.
88
139
 
89
- 2. Optimized Hashs do not collapse keys that become the same in the output. As
90
- an example, a non-String object that has a to_s() method will become the
91
- return value of the to_s() method in the output without checking to see if
140
+ 2. Optimized Hashes do not collapse keys that become the same in the output. As
141
+ an example, a non-String object that has a `to_s()` method will become the
142
+ return value of the `to_s()` method in the output without checking to see if
92
143
  that has already been used. This could occur is a mix of String and Symbols
93
144
  are used as keys or if a other non-String objects such as Numerics are mixed
94
145
  with numbers as Strings.
data/pages/Security.md CHANGED
@@ -7,7 +7,7 @@ Symbols. The same is true for auto defining classes in all versions of ruby;
7
7
  memory will also be exhausted if too many classes are automatically
8
8
  defined. Auto defining is a useful feature during development and from trusted
9
9
  sources but it allows too many classes to be created in the object load mode and
10
- auto defined is used with an untrusted source. The `Oj.strict_load()` method
10
+ auto defined is used with an untrusted source. The `Oj.safe_load()` method
11
11
  sets and uses the most strict and safest options. It should be used by
12
12
  developers who find it difficult to understand the options available in Oj.
13
13
 
@@ -21,7 +21,12 @@ class ActiveRecordResultTest < Minitest::Test
21
21
  ["row 3 col 1", "row 3 col 2"],
22
22
  ])
23
23
  #puts "*** result: #{Oj.dump(result, indent: 2)}"
24
-
25
- assert_equal Oj.dump(result, mode: :rails), Oj.dump(result.to_hash)
24
+ json_result = if ActiveRecord.version >= Gem::Version.new("6")
25
+ result.to_a
26
+ else
27
+ result.to_hash
28
+ end
29
+
30
+ assert_equal Oj.dump(result, mode: :rails), Oj.dump(json_result)
26
31
  end
27
32
  end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ ORIG_ARGV = ARGV.dup
4
+
5
+ require "active_support/core_ext/kernel/reporting"
6
+
7
+ silence_warnings do
8
+ Encoding.default_internal = Encoding::UTF_8
9
+ Encoding.default_external = Encoding::UTF_8
10
+ end
11
+
12
+ require "active_support/testing/autorun"
13
+ require "active_support/testing/method_call_assertions"
14
+
15
+ ENV["NO_RELOAD"] = "1"
16
+ require "active_support"
17
+
18
+ Thread.abort_on_exception = true
19
+
20
+ # Show backtraces for deprecated behavior for quicker cleanup.
21
+ ActiveSupport::Deprecation.debug = true
22
+
23
+ # Default to old to_time behavior but allow running tests with new behavior
24
+ ActiveSupport.to_time_preserves_timezone = ENV["PRESERVE_TIMEZONES"] == "1"
25
+
26
+ # Disable available locale checks to avoid warnings running the test suite.
27
+ I18n.enforce_available_locales = false
28
+
29
+ class ActiveSupport::TestCase
30
+ include ActiveSupport::Testing::MethodCallAssertions
31
+
32
+ # Skips the current run on Rubinius using Minitest::Assertions#skip
33
+ private def rubinius_skip(message = "")
34
+ skip message if RUBY_ENGINE == "rbx"
35
+ end
36
+
37
+ # Skips the current run on JRuby using Minitest::Assertions#skip
38
+ private def jruby_skip(message = "")
39
+ skip message if defined?(JRUBY_VERSION)
40
+ end
41
+
42
+ def frozen_error_class
43
+ Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError
44
+ end
45
+ end