ougai icon indicating copy to clipboard operation
ougai copied to clipboard

How to make Oj optional

Open ybiquitous opened this issue 4 years ago • 9 comments

Hello. I have some reason not to be able to use Oj, so is there a way to use another JSON library like the standard library JSON instead of Oj?

When I look into the code, it seems hard to replace Ougai::Serializer.for_json with some serializer without any monkey-patch.

https://github.com/tilfin/ougai/blob/73471358cc5c789b037abcab944cc1fac18353a6/lib/ougai/formatters/for_json.rb#L15

If we could make Oj an optional dependency, it would be ideal for me.

https://github.com/tilfin/ougai/blob/73471358cc5c789b037abcab944cc1fac18353a6/ougai.gemspec#L30

I would appreciate it if you would consider it. Thanks.

ybiquitous avatar Jan 27 '21 08:01 ybiquitous

I use Oj instead of standard JSON for two reasons.

First, it's faster. Second, it doesn't fail even when garbled string is mixed in values of structured data.

I actually fell into this trap when logging info entered by users in mobile apps. If you still intend to deal with this issue, I will consider implementation.

Thanks.

tilfin avatar Jan 27 '21 08:01 tilfin

Thank you so much for your quick response!

I fully understand the benefits of Oj, but I think making the Ougai serializer pluggable will be very useful for this gem's fan. (especially, users like me who cannot use Oj for some reason 😅 )

I'd appreciate it so much if you could proceed with this issue.

ybiquitous avatar Jan 27 '21 09:01 ybiquitous

I understood it.

I think that your purpose can be achieved by the following code.

require 'rubygems'
require 'ougai'
require 'json'

class StandardJSONSerializer < Ougai::Serializer
  def serialize(data)
    JSON.generate(data)
  end
end

module Ougai
  class Serializer
    def self.for_json
      StandardJSONSerializer.new
    end
  end
end

logger = Ougai::Logger.new(STDOUT)
logger.info('log')

tilfin avatar Jan 27 '21 09:01 tilfin

I'd suggest using multi_json, like many other gems.

Freaky avatar Jan 31 '21 23:01 Freaky

I decided that Ougai should not use multi_json from now based on the following links.

  • https://github.com/intridea/multi_json/issues/200#issuecomment-689087204
  • https://github.com/intridea/multi_json/pull/113

I want to keep Oj and JrJackson as default, but allow users to change their custom serializer.

tilfin avatar Feb 20 '21 15:02 tilfin

Sounds good. How will not Ougai install Oj if a user wants to install another JSON library? (in other words, will Oj always be installed?)

ybiquitous avatar Feb 22 '21 01:02 ybiquitous

Ougai have already been used by a considerable number of applications, so I'm carefully considering how to make the users install OJ(JrJackson) separately.

tilfin avatar Feb 24 '21 01:02 tilfin