Sha256: 9d0c2d480fa87caca35cfffc4150f1ea6fce940026a31d56717dd40ee8258c44

Contents?: true

Size: 934 Bytes

Versions: 6

Compression:

Stored size: 934 Bytes

Contents

# frozen_string_literal: true

class Serega
  module Utils
    class AsJSON
      DOUBLE_QUOTE = '"'

      class << self
        def call(data, to_json:)
          case data
          when Hash
            data.each_with_object({}) do |(key, value), new_data|
              new_key = key.to_s
              new_value = call(value, to_json: to_json)
              new_data[new_key] = new_value
            end
          when Array
            data.map { |value| call(value, to_json: to_json) }
          when NilClass, Integer, Float, String, TrueClass, FalseClass
            data
          when Symbol
            data.to_s
          else
            res = to_json.call(data)
            if res.start_with?(DOUBLE_QUOTE) && res.end_with?(DOUBLE_QUOTE)
              res.delete_prefix!(DOUBLE_QUOTE)
              res.delete_suffix!(DOUBLE_QUOTE)
            end
            res
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
serega-0.1.5 lib/serega/utils/as_json.rb
serega-0.1.4 lib/serega/utils/as_json.rb
serega-0.1.3 lib/serega/utils/as_json.rb
serega-0.1.2 lib/serega/utils/as_json.rb
serega-0.1.1 lib/serega/utils/as_json.rb
serega-0.1.0 lib/serega/utils/as_json.rb