Last active
August 31, 2020 05:52
-
-
Save h-shima/7dc9c7a703686a37dc510157a0957904 to your computer and use it in GitHub Desktop.
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
CSV::Writer#<<メソッドに関する質問です | |
3.0.1以前と3.0.2以降で CSV::Writer#<<メソッド内部の挙動に違いがあるように見えるのですが、これは意図的なものでしょうか? | |
### 相違点 | |
#### 3.0.1 | |
1行ずつencodeしてからStringIO#<<で文字列をappendしている。 | |
#### 3.0.2 | |
encodeせずにappendして、レシーバの文字コードに変換している。 | |
### 質問 | |
例えば、1行目にWindow-31Jの文字列をappendして、CSV.generateのencodingオプションでもWindow-31Jを指定して、2行目でWindow-31Jにはencodeできない文字を入れると、以前はencodeしてからappendという順番だったのでencodeできないというところでエラーが発生していたが、現在はencodeせずにappendしているので、appendするときにエラーが発生するようになっている。 | |
テストケース | |
``` | |
require 'csv' | |
require 'pry' | |
class Foo | |
def generate | |
CSV.generate(encoding: Encoding::Windows_31J) do |csv| | |
csv << ["\uFF5E"] # StringIOにバグがあるため、Windows-31Jにしか存在しない文字を渡している。 https://github.com/ruby/stringio/issues/13 | |
csv << ["\u2783"] | |
end | |
end | |
end | |
RSpec.describe CSV do | |
describe 'Foo#generate' do | |
let(:foo) { Foo.new.generate } | |
subject { foo } | |
describe '#encoding' do | |
subject { foo.encoding.to_s } | |
# encodeメソッドがデフォルトの状態 | |
it { is_expected.to eq 'Windows-31J' } | |
end | |
end | |
end | |
``` | |
3.0.1での実行結果 | |
``` | |
Encoding::UndefinedConversionError: | |
U+2783 from UTF-8 to Windows-31J | |
``` | |
3.0.2での実行結果 | |
``` | |
Encoding::CompatibilityError: | |
incompatible character encodings: Windows-31J and UTF-8 | |
``` | |
これは、encodeできる、できないなどの取り回しは全てStringIOの責務で行うことになったということでしょうか? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment