Skip to content

Instantly share code, notes, and snippets.

@oakbow
Last active August 29, 2015 13:57
Show Gist options
  • Save oakbow/9826806 to your computer and use it in GitHub Desktop.
Save oakbow/9826806 to your computer and use it in GitHub Desktop.
exchange character encoding from UTF-8 to SJIS, for IE or Excel users. ref: http://qiita.com/Oakbow/items/a62d1de9c62ee8fa2eb2
# IEのダウンロードファイル名の文字化け対応
def filename_for_download(filename)
if request.env['HTTP_USER_AGENT'] =~ %r{MSIE} && request.env['HTTP_ACCEPT_LANGUAGE'] =~ /^ja/
filename = Utf8ToWin31jCodeConverter.convert_to_windows31j(filename)
end
filename
end
class Utf8ToWin31jCodeConverter
class << self
def convert_table
[
%w|301C FF5E|, # WAVE DASH => FULLWIDTH TILDE
%w|2212 FF0D|, # MINUS SIGN => FULLWIDTH HYPHEN-MINUS
%w|00A2 FFE0|, # CENT SIGN => FULLWIDTH CENT SIGN
%w|00A3 FFE1|, # POUND SIGN => FULLWIDTH POUND SIGN
%w|00AC FFE2|, # NOT SIGN => FULLWIDTH NOT SIGN
%w|2014 2015|, # EM DASH => HORIZONTAL BAR
%w|2016 2225|, # DOUBLE VERTICAL LINE => PARALLEL TO
]
end
def convert_to_windows31j(utf_8_str)
utf_8_str.encode!("UTF-8-MAC", "UTF-8", :invalid => :replace, :undef => :replace, :replace => '')
utf_8_str.encode!("UTF-8")
utf_to_win31j_safe_str = Utf8ToWin31jCodeConverter.convert(utf_8_str)
utf_to_win31j_safe_str.encode 'WINDOWS-31J'
end
def convert(str)
result = str.dup
convert_table.each do |arr|
from = code_point_to_char(arr[0])
to = code_point_to_char(arr[1])
result = result.gsub(from, to)
end
result
end
def code_point_to_char(code_point)
code_point.to_i(16).chr("UTF-8")
end
def char_to_code_point(char)
char[0].unpack("U*").first.to_s(16).upcase
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment