LoginSignup
0
0

More than 3 years have passed since last update.

RailsでUTF-16のファイルを作成する

Last updated at Posted at 2020-01-16

[01/17:追記]
コメントでいただいた意見を元に検証をしたところforce_encodingを使用しているのが問題でした。
String#encodeを使用してエンコードを書き換えればそのままUTF-16のファイルとして出力出来ました。

経緯

Ruby on RailsでUTF-16のファイルを作成する必要があったので、
その時の処理を備忘録として書き留めて置きたいと思います。

ソース

qiita.rb
/**
 * xml作成
 */
def create_xml
    view_context = ActionView::Base.new
    view_context.assign(data: "aaaaaaaaaa")
    tmp = File.read(Settings.template)
    # view_context.render(inline: tmp).force_encoding("utf-16")
    view_context.render(inline: tmp).encode("utf-16")
end
create_file.rb
/**
 * ファイル作成(ローカルにファイルを作成する)
 * @param xml バイナリデータ
 * @param file_name ファイル名
 * @param upload_time 作成日時
 */
def put_string_file(xml, file_name, upload_time)
    # ディレクトリとファイルの定義
    dir = "#{Rails.root}/storage/#{upload_time}/"
    file = "#{dir}#{file_name}"
    # フォルダがなければ作成
    FileUtils.mkdir_p(dir) unless File.directory?(dir)

    # xmlをファイルに出力
    File.binwrite(file, StringIO.new(xml).read)
    # 作成されたファイルを読み込みUTF-16に変換する
    # File.open(file, 'r'){ |f|
    #  buffer = f.read();
    #  buffer = buffer.encode("UTF-16", "UTF-8", :invalid => :replace, :undef => :replace, :replace => '*')
    #  f = File.open(file, 'w:UTF-16:UTF-8')
    #  f.write(buffer)
    #}
  end

まとめ

一発でUTF-16のファイルを作成できないかなと調べてみましたが、見つからず。
一旦UTF-8でファイルを作成し、UTF-16に変換してと手間をかける方法しか浮かばなかったです。
改善点などあれば情報求む。

0
0
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0