Created
December 13, 2011 17:54
-
-
Save littlefyr/1473114 to your computer and use it in GitHub Desktop.
Load Files with the right encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#This should work for most cases, at least on OSX | |
def open_encoded file_name, &block | |
fcheck = `file --mime #{file_name}` | |
charset = fcheck.split(/charset=/).last.gsub(/\s+/, ' ').strip | |
if ["unknown-8bit", "iso-8859-1"].include?(charset) | |
encoding = Encoding::Windows_1250 #This is a guess. In the case of the files I'm working with, this is true. YMMV | |
else | |
begin | |
encoding = Encoding.find(charset) | |
rescue Exception => e | |
encoding = Encoding::UTF_8 | |
end | |
end | |
if block_given? | |
File.open(file_name, "r", :external_encoding => encoding, :internal_encoding =>Encoding::UTF_8, &block) | |
else | |
File.open(file_name, "r", :external_encoding => encoding, :internal_encoding =>Encoding::UTF_8) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment