Sha256: 9fa4e2b8380a95699f30bc67abbd7773f5b097e7979ab564fa7d35c8024f6618

Contents?: true

Size: 1.8 KB

Versions: 4

Compression:

Stored size: 1.8 KB

Contents

# Help interpret the general type of a particular object
class Interpreter
  class << self
    # @return [Error] XML Errors found in interpreting response
    attr_accessor :xml_errors

    # @return [Error] JSON Errors found in interpreting response
    attr_accessor :json_errors

    # @param [Object] response API response
    # @return [Symbol] Type of provided response
    def response_type_for(response)
      @xml_errors = nil
      @json_errors = nil
      @response = response
      if @response.is_a? String
        if xml?
          :xml
        elsif json?
          :json
        else
          :string
        end
      elsif response.is_a? Hash
        :hash
      elsif response.is_a?(Nokogiri::XML::NodeSet) || response.is_a?(Nokogiri::XML::Document)
        :xml
      else
        :unknown
      end
    end

    # @return [Boolean] Whether response has tag like syntax similar to XML. Could be a syntax error occurred
    def looks_like_xml?
      @response[0] == '<' && @response[-1] == '>'
    end

    # @return [Boolean] Whether response has bracket like syntax similar to JSON. Could be a syntax error occurred
    def looks_like_json?
      @response[0] == '{' && @response[-1] == '}'
    end

    # @return [String] Description of error
    def diagnose_error
      return xml_errors if looks_like_xml?

      return json_errors if looks_like_json?

      ''
    end

    # @return [Boolean] Whether valid XML
    def xml?
      Nokogiri::XML(@response) { |config| config.options = Nokogiri::XML::ParseOptions::STRICT }
    rescue Nokogiri::XML::SyntaxError => xml_error
      self.xml_errors = xml_error
      false
    end

    # @return [Boolean] Whether valid JSON
    def json?
      JSON.parse(@response)
    rescue JSON::ParserError=> json_error
      self.json_errors = json_error
      false
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
soaspec-0.2.29 lib/soaspec/interpreter.rb
soaspec-0.2.28 lib/soaspec/interpreter.rb
soaspec-0.2.27 lib/soaspec/interpreter.rb
soaspec-0.2.26 lib/soaspec/interpreter.rb