Add sort_keys option in the generator.#1043
Conversation
|
THanks for handling this, however in lieu of #1038, I think a |
No problem. I can try to take a stab at that tonight night/this weekend. I think it should be as simple as accepting a proc and passing it to |
|
I added the ability to pass a Proc which accepts two Note that a boolean ( |
| if (rb_obj_is_proc(sort_keys)) { | ||
| sorted_array = rb_funcall_with_block(obj, rb_intern("sort"), 0, NULL, sort_keys); | ||
| } else { | ||
| sorted_array = rb_funcall(obj, rb_intern("sort"), 0); | ||
| } | ||
| obj = rb_funcall(sorted_array, rb_intern("to_h"), 0); |
There was a problem hiding this comment.
Sorry, for not immediately communicating in details what I had in mind, I was traveling.
Based on the type of sorting json-normalization needs: https://github.com/dryruby/json-canonicalization/blob/a85e688a4a593ed6b28e5aa4610c996828c13ada/lib/json/canonicalization.rb#L64-L78
I think it would be better if the sort proc would just take the entire hash at once, and return a sorted hash.
As for the sort: true argument, that's great, that's what I had in mind, but we might be better to just convert it into a proc early on the Ruby side:
def generate(..., options)
if options[:sort_keys] == true
options = options.merge(sort_keys: ->(hash) { hash.sort.to_h }
end
...
end
I had some time last night so I decided to see how hard it would be to implement a sort_keys option to the generator. This adds support to the C extension, Java extension and truffleruby implementation.