0
1

More than 3 years have passed since last update.

twitterアイコンをs3に保存する

Posted at

やること

twitterログインで取得してくるtwitterアイコンのリンクがすぐに切れてしまうのでs3に保存する。

実装内容

  • rails
  • 画像保存はcarrierwaveを経由でs3

twitteromniauthの実装

上記記事が分かりやすかった

新規登録時にのみ画像保存の処理

omniauthで下記の処理を書いている

user.rb
class User < ApplicationRecord
  mount_uploader :image_url, ImageUploader
  #引数に関連するユーザーが存在すればそれを返し、存在しまければ新規に作成する
  def self.find_or_create_from_auth_hash(auth_hash)
  #OmniAuthで取得した各データを代入していく
      provider = auth_hash[:provider]
      uid = auth_hash[:uid]
      nickname = auth_hash[:info][:nickname]
      image = auth_hash[:info][:image]

      User.find_or_initialize_by(provider: provider, uid: uid) do |user|
        if user.new_record?
          user.nickname = nickname
          user.remote_image_url = image_url
          user.save
        end
      end
    end
end

find_or_initialize_byはuserを探してあったらそれを取得、なかったら新規作成するもの。find_or_create_byと違うのはfind_or_create_byは保存までやってくれる。新規登録のみの処理を入れたい場合、new_record?で新規作成かを条件分岐してからsaveできるfind_or_initialize_byでやる。

画像保存をcarrierwave

画像保存でやっているのは下記の処理

  • twitterからアイコンのurlを取得
  • そのurlから画像をdl
  • そしてその落とした画像をs3に保存

この処理をremote_xxxx_urlメソッドだと簡単にできる。

0
1
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
0
1