Skip to content

Instantly share code, notes, and snippets.

@mattetti
Forked from etozzato/expires_at.rb
Created August 4, 2010 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattetti/508895 to your computer and use it in GitHub Desktop.
Save mattetti/508895 to your computer and use it in GitHub Desktop.
# expires_at '21:30', :public => true, :private => false
# will set max-age to the amount of seconds between now and tomorrow at 9:30PM
module ExpiresAt
def self.included(base)
base.send(:include, InstanceMethods)
end
module InstanceMethods
def expires_at_midnight(options={})
now = Time.now
cache_control = response.headers["Cache-Control"].split(",").map {|k| k.strip }
cache_control << "max-age=#{(now.end_of_day - Time.now).to_i}"
cache_control.delete("no-cache")
if options[:public]
cache_control.delete("private")
cache_control << "public"
else
cache_control << "private"
end
cache_control += options.symbolize_keys.reject{|k,v| k == :public || k == :private }.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"}
response.headers["Cache-Control"] = cache_control.join(', ')
end
end
def expires_at(time='00:00', options = {})
h, m = time.to_s.split(':')
h = h.to_i
m = m.to_i
h = 0 unless h.between?(0, 23)
m = 0 unless m.between?(0, 59)
seconds = ((Time.now.end_of_day + h.hours + m.minutes) - Time.now).to_i
cache_control = response.headers["Cache-Control"].split(",").map {|k| k.strip }
cache_control << "max-age=#{seconds}"
cache_control.delete("no-cache")
if options[:public]
cache_control.delete("private")
cache_control << "public"
else
cache_control << "private"
end
cache_control += options.symbolize_keys.reject{|k,v| k == :public || k == :private }.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"}
response.headers["Cache-Control"] = cache_control.join(', ')
end
end
end
ActionController::Base.send(:include, ExpiresAt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment