class Nokogiri::HTML::Document::EncodingReader

def self.detect_encoding(chunk)

def self.detect_encoding(chunk)
  m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
    return Nokogiri.XML(m[1]).encoding
  handler = SAXHandler.new
  parser = Nokogiri::HTML::SAX::Parser.new(handler)
  catch(:found) {
    parser.parse(chunk)
  }
  handler.encoding
rescue => e
  nil
end