module OEmbed::Formatter

def decode(format, value)

#=> {"version": "1.0", "type": "link", "title": "Some Cool News Article"}
OEmbed::Formatter.decode('json', value)
value = '{"version": "1.0", "type": "link", "title": "Some Cool News Article"}'
For example:

a String or IO containing the response from an oEmbed server.
be the name of the response format (e.g. 'json'). The value should be
Convert the given value into a nice Hash of values. The format should
def decode(format, value)
  supported?(format)
  
  begin
    case format.to_s
    when 'json'
      begin
        JSON.decode(value)
      rescue JSON.backend.parse_error
        raise OEmbed::ParseError, $!.message
      end
    when 'xml'
      begin
        XML.decode(value)
      rescue XML.backend.parse_error
        raise OEmbed::ParseError, $!.message
      end
    end
  rescue
    raise OEmbed::ParseError, "#{$!.class}: #{$!.message}"
  end
end

def default

Returns the default format for OEmbed::Provider requests as a String.
def default
  # Listed in order of preference.
  %w{json xml}.detect { |type| supported?(type) rescue false }
end

def supported?(format)

OEmbed::FormatNotSupported.
true if there is a valid backend. If there is no backend, raises
Given the name of a format we want to know about (e.g. 'json'), returns
def supported?(format)
  case format.to_s
  when 'json'
    JSON.supported?
  when 'xml'
    XML.supported?
  else
    raise OEmbed::FormatNotSupported, format
  end
end

def test_backend(backend_module)

The backend_module should be either a JSON or XML backend.
Test the given backend to make sure it parses known values correctly.
def test_backend(backend_module)
  expected = {
    "version"=>1.0,
    "string"=>"test",
    "int"=>42,
    "html"=>"<i>Cool's</i>\n the \"word\"!",
  }
  
  given_value = case backend_module.to_s
  when /OEmbed::Formatter::JSON::Backends::/
    <<-JSON
ion":"1.0", "string":"test", "int":42,"html":"<i>Cool's</i>\\n the \\"word\\"\\u0021"}
    JSON
  when /OEmbed::Formatter::XML::Backends::/
    <<-XML
version="1.0" encoding="utf-8" standalone="yes"?>
d>
sion>1.0</version>
ing>test</string>
>42</int>
l>&lt;i&gt;Cool's&lt;/i&gt;\n the &quot;word&quot;&#x21;</html>
ed>
    XML
  else
    nil
  end
  
  actual = backend_module.decode(given_value)
  
  # For the test to be true the actual output Hash should have the
  # exact same list of keys _and_ the values should be the same
  # if we ignoring typecasting.
  actual.keys.sort == expected.keys.sort &&
    !actual.detect { |key, value| value.to_s != expected[key].to_s }
end