LoginSignup
2
3

More than 5 years have passed since last update.

【Rails】メモリ上の画像をそのままcarrierwaveに渡す

Posted at

carrierwaveは、Railsアプリケーションで、画像ファイルをアップロードなどを助けてくれるツールとしてとてもポピュラーです。

https://github.com/carrierwaveuploader/carrierwave
CarrierWave + Rails 5.1で画像アップローダー
Rails 超お手軽な画像アップローダー CarrierWave の使い方

コード上で作成した画像をそのまま、carrierwaveに渡す方法をメモとして残しておきます。
1年ほど前に書いたものなので、今のバージョンではできるようになっているかもしれませんね。

実装方法

まず、StringIOクラスを継承したCarrierStringIOクラスを作ります。

class CarrierStringIO < StringIO
  def initialize(*args)
    super(*args[2..-1])
    @filepath = args[0]
    @content_type = args[1]
  end 

  def original_filename
    @filepath
  end

  def content_type
    @content_type
  end
end

そして、お決まりでmount_uploader を設定しますが、モデルのimage_dataに代入されたらCarrierStringIOクラスを自身のimageに代入するようにします。
これ、もっといい方法があるかもしれませんが、私の脳みそじゃこれぐらいしかできません。

class Hoge < ActiveRecord::Base
  mount_uploader :image, ImageUploader

  def image_data=(data)
    content_type = "image/png"
    io = CarrierStringIO.new("title.png", content_type, data)
    self.image = io
  end
end

結果

  • これでできるようになります
  • もっといい方法あれば教えてください
2
3
0

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
2
3