Skip to content

Instantly share code, notes, and snippets.

@hughevans
Created October 27, 2014 00:12
Show Gist options
  • Save hughevans/e4ebc1cfad9e175413a1 to your computer and use it in GitHub Desktop.
Save hughevans/e4ebc1cfad9e175413a1 to your computer and use it in GitHub Desktop.
Invalidate CloudFront cache of S3 assets in Comfortable Mexican Sofa after update or destroy using the Fog gem
module YourApp
class Application < Rails::Application
config.after_initialize do
Comfy::Cms::File.send(:include, ComfyCloudfront)
end
end
end
require 'comfy_cloudfront'
module ComfyCloudfront
def self.included(base)
base.after_validation :invalidate_cloudfront, on: :update
end
def destroy
super if invalidate_cloudfront
end
def invalidate_cloudfront
begin
cdn = Fog::CDN.new({
provider: 'AWS',
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
})
cdn.post_invalidation(ENV['CLOUDFRONT_DISTRIBUTION_ID'], ["/#{file.path}", "/#{file.path(:cms_thumb)}"])
rescue Excon::Errors::BadRequest
return false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment