oj: "bigdecimal_as_decimal: true" doesn't seem to work when rendering JSON in controller
Hello,
I’ve prepared a very simple Rails 5 app demonstrating a problem with the bigdecimal_as_decimal setting: https://github.com/michaltrzcinka/oj-issue
In oj.rb initializer here https://github.com/michaltrzcinka/oj-issue/blob/master/config/initializers/oj.rb I set this option to true, and in controller here https://github.com/michaltrzcinka/oj-issue/blob/master/app/controllers/welcome_controller.rb I render a very simple hash with a BigDecimal value. When I test it, the code renders the following:
{"x":"10.0"}
I would expect:
{"x":10.0}
I’ve also found an interesting difference when playing in pry:
[2] pry(main)> Oj::Rails::Encoder.new.encode({x: 10.to_d})
=> "{\"x\":10.0}"
[3] pry(main)> Oj::Rails::Encoder.new({}).encode({x: 10.to_d})
=> "{\"x\":\"10.0\"}"
Oj::Rails::Encoder is called with an options hash here https://github.com/rails/rails/blob/master/activesupport/lib/active_support/json/encoding.rb#L22 and it seems to break this setting?
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 18 (12 by maintainers)
Okay, I looked into the issue a bit more. I don’t think there are any changes necessary. The steps to take that should work or at least work for me in tests is to do this.
The calls to Oj::Rails.set_encoder and Oj::Rails.optimize should be called first and they will reset the defaults to match those for rails. After that the bigdecimal_as_decimal can be reset to true.