class Shoji::UTF8File
Constants
- NKF2ICONV
Attributes
tempfile[R]
Public Class Methods
convert(filename) { |path| ... }
click to toggle source
# File lib/shoji/utf8_file.rb, line 5 def self.convert(filename, &block) encoding = guess_encoding(filename) raise "Couldn't detect encoding" unless encoding fp = make_instance(filename, encoding) if block_given? begin yield(fp.path) ensure fp.delete end else fp end end
guess_encoding(filename)
click to toggle source
# File lib/shoji/utf8_file.rb, line 38 def self.guess_encoding(filename) NKF2ICONV[NKF.guess(read_lines(filename, 3))] end
new(source, type)
click to toggle source
# File lib/shoji/utf8_file.rb, line 20 def initialize(source, type) @filename = nil; @tempfile = nil case type when :filename then @filename = source when :tempfile then @tempfile = source else raise "Unexpected type=#{type}" end end
Private Class Methods
make_instance(filename, encoding)
click to toggle source
# File lib/shoji/utf8_file.rb, line 57 def self.make_instance(filename, encoding) return new(filename, :filename) if encoding == 'UTF-8' if winfile?(filename) && encoding == 'SJIS' encoding = 'CP932' end tf = Tempfile.new('file-path') tf.write File.open(filename, "r:#{encoding}:UTF-8").read tf.close new(tf, :tempfile) end
read_lines(filename, max = 1)
click to toggle source
# File lib/shoji/utf8_file.rb, line 67 def self.read_lines(filename, max = 1) lines = [] index = 0 File.foreach(filename, encoding: 'BINARY') do |line| lines << line index += 1 break if index >= max end lines.join('') end
winfile?(filename)
click to toggle source
# File lib/shoji/utf8_file.rb, line 49 def self.winfile?(filename) line = read_lines(filename, 1) if line =~ /\r\n$/ true else false end end
Public Instance Methods
delete()
click to toggle source
# File lib/shoji/utf8_file.rb, line 32 def delete return false unless @tempfile @tempfile.close(true) @tempfile = nil true end
path()
click to toggle source
# File lib/shoji/utf8_file.rb, line 28 def path return @filename if @filename @tempfile.path end