Sha256: 64b4ff99b582c01be77b582c7b11fa923ae88d34794108120d3a93de9fb59f51

Contents?: true

Size: 1.15 KB

Versions: 5

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

##
# Tries to parse a JSON string and return the corresponding JSON object (Ruby hash, array, etc).
# Returns default value when fails to parse (default value is set to `nil` by default).
#
# IMPORTANT: `JSON::ParseError` is not the only exception that can be raised by `JSON.parse`.
# Check this link (`Ctrl + f' for `error'):
# https://github.com/ruby/ruby/blob/master/ext/json/lib/json.rb
#
module ConvenientService
  module Examples
    module Standard
      class RequestParams
        module Utils
          module JSON
            class SafeParse < ConvenientService::Command
              attr_reader :json_string, :default_value

              def initialize(json_string, default_value: nil)
                @json_string = json_string
                @default_value = default_value
              end

              def call
                return default_value unless json_string.instance_of?(::String)

                begin
                  ::JSON.parse(json_string)
                rescue
                  default_value
                end
              end
            end
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
convenient_service-0.17.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.16.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.15.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.14.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.13.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb