Module: Aio::Base::Toolkit::String

Defined in:
lib/aio/base/toolkit/string.rb

Class Method Summary collapse

Class Method Details

.safe(str) ⇒ Object

终极解决方案遇到了 invalid byte sequence in UTF-8 (ArgumentError) 问题解决办法参考 stackoverflow.com/questions/29877310/invalid-byte-sequence-in-utf-8-argumenterror



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/aio/base/toolkit/string.rb', line 7

def safe(str)
  case Aio::Base::Toolkit::OS.os_family
  when "unix"
    if ! str.valid_encoding?
      str = str.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
    end 

    # UTF-8 编码前缀删除
    # 参考: https://estl.tech/of-ruby-and-hidden-csv-characters-ef482c679b35
    str.sub!("\xEF\xBB\xBF", '')

  when "windows"
    #str = str.force_encoding("UTF-8")
    str = str.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
    str.sub!("\xEF\xBB\xBF", '')
  end
  return str 
end

.safe_path(path) ⇒ Object

改写成安全的Windows书写方式



27
28
29
30
31
# File 'lib/aio/base/toolkit/string.rb', line 27

def safe_path(path)
  if Aio::Base::Toolkit::OS.windows?
    path.gsub!("/", "\\")
  end
end