Last active
December 10, 2015 16:18
-
-
Save coop/4460058 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Conditional GET Support for a collection of ActiveRecord objects | |
# | |
# Useful in controllers when you want to support conditional get in | |
# index actions. | |
# | |
# example: | |
# class PostsController | |
# def index | |
# if stale?(conditional_get_collection) | |
# respond_with collection | |
# end | |
# end | |
# | |
# def collection | |
# current_user.posts | |
# end | |
# | |
# def conditional_get_collection | |
# ConditionalGETCollection.new current_user: current_user, | |
# collection: collection | |
# end | |
# end | |
class ConditionalGETCollection | |
def initialize attributes = nil | |
attributes ||= {} | |
@collection = attributes.fetch(:collection) { NullCollection.new } | |
@hasher = attributes.fetch(:hasher) { Digest::MD5 } | |
@current_user = attributes[:current_user] || NullUser.new | |
end | |
def cache_key | |
current_user_id = @current_user.id | |
seconds_since_epoch = updated_at.to_i | |
count = @collection.count | |
@hasher.hexdigest [current_user_id, seconds_since_epoch, count].join('-') | |
end | |
def updated_at | |
@collection.maximum(:updated_at) | |
end | |
class NullUser | |
def id | |
0 | |
end | |
end | |
class NullCollection | |
def count | |
0 | |
end | |
def maximum attribute = :updated_at | |
Time.new(1970, 1, 1, 0, 0, 0, 0).in_time_zone('UTC') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment