📂

ActionDispatch::Http::UploadedFileを紐解く

2020/12/25に公開

TGIFですね。

昨日のエラーを解決する中で、気になる表示がありました。
Active Storageで画像ファイルを送信する時に現れるこのオブジェクト。

"ActionDispatch::Http::UploadedFile"

これは一体なんなんだい?と言う記事です。

その正体は??

Dispatchって?

https://dictionary.cambridge.org/dictionary/english/dispatch

ケンブリッジディレクトリでの定義は以下の通り。

to send something, especially goods or a message, somewhere for a particular purpose:

ある目的のためにサムシィング(画像ファイル)をどこか(Active Storage)に送り出すこと、かな。

ActionDispatch::Http::UploadedFileの定義

https://api.rubyonrails.org/v6.0.3.3/classes/ActionDispatch/Http/UploadedFile.html

Models uploaded files.
The actual file is accessible via the tempfile accessor, though some of its interface is available directly for convenience.
Uploaded files are temporary files whose lifespan is one request. When the object is finalized Ruby unlinks the file, so there is no need to clean them with a separate maintenance task.

最初の1行目がよく分かりません。(残念)

要するに、アップロードしたいファイルをリクエストに一度だけ持たせることができるモジュール。(多分)

上記ではtempfile accessorがメインのアクセサーになっているとのこと。
と言うことは、attr_accessorでtempfileが指定されているのか。確認しました。

class UploadedFile

      # The basename of the file in the client.
      attr_accessor :original_filename

      # A string with the MIME type of the file.
      attr_accessor :content_type

      # A +Tempfile+ object with the actual uploaded file. Note that some of
      # its interface is available directly.
      attr_accessor :tempfile

      # A string with the headers of the multipart request.
      attr_accessor :headers

#continuing 

tempfleの他にも三つのアクセサーが指定されていました。

確かにさっきのターミナル画面にもあったなぁ。

SOTD

と言うことで、"ActionDispatch::Http::UploadedFile"と言うものをなんとなく理解できたも。こうやって理解を深めておくと、エラーが出た時にこのオブジェクトは大丈夫!と消去法が早くなるものですね。

https://github.com/rails/rails/blob/070d4afacd3e9721b7e3a4634e4d026b5fa2c32c/actionpack/lib/action_dispatch/http/upload.rb

ご参考までに。。

Discussion