Sha256: 097ada49692c4d99385d8c1724331ac198dbd5899a66afb0d83dcb3701ece38b

Contents?: true

Size: 1.14 KB

Versions: 8

Compression:

Stored size: 1.14 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 RequestParams
        module Utils
          module JSON
            class SafeParse < Support::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

8 entries across 8 versions & 1 rubygems

Version Path
convenient_service-0.12.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.11.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.10.1 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.10.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.9.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.8.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.7.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb
convenient_service-0.6.0 lib/convenient_service/examples/standard/request_params/utils/json/safe_parse.rb