简体   繁体   中英

stale? method in rails. What does it do?

I don't understand the documentation here

The point of confusing is this for me: Why do you set etag or last_modified on the response? Isn't the client the one sending an etag and a if-modified-since header? Once the server (or proxy server) receives these client headers, isn't the server checking to see if the resource's etag and modified date match? The documentation suggest that the request is generated from scratch and not the data? Also, why are we setting the etag and last_modified on the response? Isn't it set by the client?

stale?(options) protected Sets the etag and/or last_modified on the response and checks it against the client request. If the request doesn't match the options provided, the request is considered stale and should be generated from scratch. Otherwise, it's fresh and we don't need to generate anything and a reply of "304 Not Modified" is sent.

Parameters:

:etag :last_modified :public By default the Cache-Control header is private, set this to true if you want your application to be cachable by other devices (proxy caches).

What is it going? So some client request is coming in with an etag (some hash) and we check to see if that request is equal to the options in our controller that we set using stale? Here is my controller:

format.json_v20150501 do
          expires_in 30.minutes, public: true
          if stale?(last_modified: last_modified_for_models(recipes), etag: etag_for_models(recipes))
            render json: recipes,
              compact: true,
              serializer: PaginationSerializer,
              each_serializer: Api::V20150315::RecipeSerializer
          end
        end

I don't get what is happening...

stale? checks the options provided (those args) to determine whether the object has been modified and therefore needs to be regenerated (in case of cacheing).

regarding the etags, reading this might be helpful: http://blog.bigbinary.com/2016/03/08/rails-5-switches-from-strong-etags-to-weak-tags.html?utm_source=rubyweekly&utm_medium=email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM