LoginSignup
1
0

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す20(ActiveStorage::FileNotFoundError編)

Posted at

はじめに

Rails 6 に追加されそうな新機能を試す第20段。 今回のちょい足し機能は、 ActiveStorage::FileNotFoundError 編です。
Rails 6.0 では、 ActiveStorage::Blob#open などで対応するファイルが見つからなかったときに ActiveStorage::FileNotFoundError が発生するようになりました。

記載時点では、Rails は 6.0.0.rc1 で確認しました。Rails 6.0.0.rc1 は gem install rails --prerelease でインストールできます。

$  rails --version
Rails 6.0.0.rc1

わざと動作しないコードを書く

今回は、 ActiveStorage::FileNotFoundError が発生するようにわざと動作しないコードを作成します。

Rails6 のちょい足しな新機能を試す16(UploadedFile#to_path編) で使ったコードを修正して動作しないようにします。
User モデルの avatar_file_format メソッドを動作しないように修正します。

app/models/user.rb
class User < ApplicationRecord
  ...
  private

  def avatar_file_format
    avatar.blob.open do |file|
      header = File.read file, 8
      if header != PNG_FORMAT_HEADER
        errors.add(:avatar, 'is not png format file')
      end
    end
  end
end

試してみる

Rails サーバーを立ち上げて http://localhost:3000/users/new にアクセスしてユーザー登録してみます。
アップロードする画像ファイルも指定します。
Create User ボタンを押すと ActiveStorage::FileNotFoundError が発生します。
2019-05-18-210935_790x291_scrot.png

ファイルのアップロード先に限らず、ファイルが見つからないときは、ActiveStorage::FileNotFoundError が発生するようになっています。 ファイルが見つからない場合のエラーを rescue したいときには、何も考えずに ActiveStorage::FileNotFoundError を指定しておけば良いので、便利ですね。

ソースコード

試したソースは以下にあります。
https://github.com/suketa/rails6_0_0rc1/tree/try020_active_storage_missing_file

参考情報

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