1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

railsのcookieのメソッド

Posted at

railsに使うメソッド

cookieの暗号化

Sets an encrypted cookie value before sending it to the client which
prevent users from reading and tampering with its value.
It can be read using the encrypted method cookies.encrypted[:name]

cookies.encrypted[:discount] = 45

クライアントに送信する前にクッキーの値を自動的に暗号化し、読み取り時には復号化するjarを返す
クッキーがユーザ(または第三者)によって改ざんされていた場合はnil

cookies.encrypted[:discount] = 45
#=> Set-Cookie: discount=DIQ7fw==--K3n//8vvnSbGq9dA--7Xh91HfLpwzbj1czhBiwOg==; path=/
cookies.encrypted[:discount] #=> 45

暗号化されたものを読み込むには`cookies.encryptedを使う
暗号すれば読まれないようにしているのか。

有効期限をつける

Sets a cookie that expires in 1 hour.

cookies[:login] = { value: "XJ-122", expires: 1.hour }

Sets a cookie that expires at a specific time.

cookies[:login] = { value: "XJ-122", expires: Time.utc(2020, 10, 15, 5) }

上は時間で、下は日付なのか、有効期限が設定されるといい気がする

有効期限が設定されたCookieは、Webブラウザを閉じても削除されず、有効期限が来るまでWebブラウザ上に残ります

改竄を防ぐ

Sets a signed cookie, which prevents users from tampering with its value.
It can be read using the signed method cookies.signed[:name]

cookies.signed[:user_id] = current_user.id

他のデータ型にするときはシリアライズ化する

Cookie values are String-based. Other data types need to be serialized.

cookies[:lat_lon] = JSON.generate([47.68, -122.37])

シリアライズとは

シリアライズとは、配列などをそのまま配列として保存しておきたい場合などに使用します。

ユーザがブラウザを閉じたらcookieも削除される

This cookie will be deleted when the user's browser is closed.

cookies[:user_name] = "david"

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?