Rails で Base64 エンコードされた文字を Carrierwave で保存する最も良い方法

File クラスを使うと、ストレージの読み書きが発生し、速度が落ちるため、メモリ上だけで処理を行う方針。
File クラスと同じ処理をするため、メソッドを定義する。

class StringFileIO < StringIO

  def self.create_from_canvas_base64 str
    return nil if str.nil?

    head, data = str.split ",", 2

    return nil if data.nil?

    _, mime_type = head.split /:|;/

    bin = Base64.decode64 data

    self.new bin, mime_type
  end

  def initialize blob, content_type
    super(blob)
    @content_type = content_type
    self
  end

  def original_filename
    "image"
  end

  def content_type
    @content_type
  end

end


あとは、代入するのみ

class User
  def image_str= str
    self.image = StringFileIO.create_from_canvas_base64(str)
  end
end