'Ruby-Feedparser'에 해당되는 글 1건

  1. [2006/11/23] Ruby에서 Ruby-Feedparser의 사용시 인코딩 문제

Ruby에서 Ruby-Feedparser의 사용시 인코딩 문제

[Development]

Ruby에서 Ruby-Feedparser를 사용해서 RSS1.0, RSS2.0, ATOM 형식의 feed들을 손쉽게
parsing할 수 있다. 그런데 Ruby-FeedParser의 내부에서는 모든 string을 UTF-8로 변환해서
리턴하게 된다.

textconverters.rb를 보면

  1. # Convert a text in inputenc to a text in UTF8
  2. # must take care of wrong input locales
  3. def toUTF8(inputenc)
  4.    if inputenc.downcase != 'utf-8'
  5.      # it is said it is not UTF-8. Ensure it is REALLY not UTF-8
  6.      begin
  7.        if self.unpack('U*').pack('U*') == self
  8.          return self
  9.        end
  10.      rescue
  11.        # do nothing
  12.      end
  13.      begin
  14.        return self.unpack('C*').pack('U*')
  15.      rescue
  16.        return self #failsafe solution. but a dirty one :-)
  17.      end
  18.    else
  19.      return self
  20.    end
  21.   end

이 부분에서 보면 iconv를 사용하지 않고 unpack, pack으로 인코딩을 처리하는데, 이게 한국어나
일본어에서는 깨져서 볼 수가 없게 된다. (iconv가 error-proof하지 않기 때문에 저렇게 처리했다고 한다.)
따라서 Ruby-Feedparser를 사용하는 경우에는 toUTF8 함수를 override해서 다음과 같이 변경해야,
인코딩을 제대로 처리할 수 있다.

  1. require 'feedparser'
  2. require 'iconv'
  3. class String
  4.   def toUTF8(inputenc)
  5.   if inputenc.downcase != 'utf-8'
  6.      begin
  7.        iconv = Iconv.new('UTF-8', inputenc)  # iconv를 사용해서 UTF-8로 encoding 한다.
  8.        return iconv.iconv(self)
  9.      rescue
  10.        return self #failsafe solution. but a dirty one :-)
  11.      end
  12.   else
  13.      return self
  14.   end
  15.   end
  16. end
 
2006/11/23 10:01 2006/11/23 10:01