Guest User

Untitled

a guest
Jan 23rd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. require 'net/http'
  2.  
  3. module Varnish
  4. def self.included(base)
  5. base.send :extend, ClassMethods
  6. base.send :include, InstanceMethods
  7. end
  8.  
  9. module ClassMethods
  10. # Enables edge-side-includes for the listed actions
  11. # esi :index, :show, :new
  12. def esi(*actions)
  13. after_filter lambda { response.headers['X-Varnish-Esi'] = 'true' }, :only => actions
  14. end
  15. end
  16.  
  17. module InstanceMethods
  18. # Removes an object from cache
  19. # purge("/pages/123")
  20. def purge(path)
  21. http = Net::HTTP.new(request.host, request.port)
  22. http.purge(path).code == "200"
  23. end
  24.  
  25. # Creates a new netry in varnish's ban list
  26. # ban("req.http.host == example.com && req.url ~ \.png$")
  27. def ban(value)
  28. http = Net::HTTP.new(request.host, request.port)
  29. http.ban('/', {'X-Varnish-Ban' => value}).code == "200"
  30. end
  31.  
  32. # Sets the time-to-live for an object in varnish. Can take both a Time or Integer.
  33. # cache 1.hour
  34. # cache 1.day.from_now
  35. def cache(value)
  36. if value.is_a?(Time)
  37. ttl = value.utc.to_i - Time.now.utc.to_i
  38. stale = value.utc + 1.second
  39. else
  40. ttl = value.to_i
  41. stale = ttl.from_now.utc + 1.second
  42. end
  43.  
  44. response.headers['X-Fresh-Until'] = stale.strftime("%a, %d %b %Y %H:%M:%S GMT")
  45. response.headers['X-Varnish-Ttl'] = ttl.to_s
  46. end
  47.  
  48. # Sets the Cache-Control header for the response, this was taken from Sinatra.
  49. # cache_control :public, :max_age => 1.hour
  50. # cache_control :private, :must_revalidate
  51. def cache_control(*values)
  52. if values.last.kind_of?(Hash)
  53. hash = values.pop
  54. hash.reject! { |k,v| v == false }
  55. hash.reject! { |k,v| values << k if v == true }
  56. else
  57. hash = {}
  58. end
  59.  
  60. values = values.map { |value| value.to_s.tr('_','-') }
  61. hash.each do |key, value|
  62. key = key.to_s.tr('_', '-')
  63. value = value.to_i if key == "max-age"
  64. values << [key, value].join('=')
  65. end
  66.  
  67. response['Cache-Control'] = values.join(', ') if values.any?
  68. end
  69. end
  70. end
Add Comment
Please, Sign In to add comment