Sha256: 6bf8cfbaa49681858b9ed11f818ca24ea53d578a09d1f1c0b9ce8359cf44c487

Contents?: true

Size: 1.21 KB

Versions: 4

Compression:

Stored size: 1.21 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
      module V1
        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
end

Version data entries

4 entries across 4 versions & 1 rubygems

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