Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CSS Cache Bust Jekyll Plugin
module Jekyll
module CacheBust
class CacheDigester
require 'digest/md5'
attr_accessor :file_name, :directory
def initialize(file_name:, directory: nil)
self.file_name = file_name
self.directory = directory
end
def digest!
[file_name, '?', Digest::MD5.hexdigest(file_contents)].join
end
private
def directory_files_content
target_path = File.join(directory, '**', '*')
Dir[target_path].map{|f| File.read(f) unless File.directory?(f) }.join
end
def file_content
FIle.read(file_name)
end
def file_contents
is_directory? ? file_content : directory_files_content
end
def is_directory?
directory.nil?
end
end
def bust_css_cache(file_name)
CacheDigester.new(file_name: file_name, directory: 'assets/_sass').digest!
end
end
end
Liquid::Template.register_filter(Jekyll::CacheBust)
@DavidMaarek
Copy link

DavidMaarek commented Nov 14, 2022

Hi !

Thank you very much for this plugin which helped me a lot.
I also wanted to add "bust cache" for images and other resources in my application, so I attempted to modify the plugin so that it could be used on any type of resource.

Here is the modification of the directory_files_content function :

def directory_files_content
   if directory == '_scss'
      target_path = File.join(directory, '**', '*')
   else
      target_path = File.join(directory, file_name)
   end
   Dir[target_path].map{|f| File.read(f) unless File.directory?(f) }.join
end

And the modification of the bust_cache function :

def bust_cache(file_name, directory)
   if directory != '.'
     CacheDigester.new(file_name: file_name, directory: directory).digest!
   else
     CacheDigester.new(file_name: file_name, directory: File.join(File.dirname('../'))).digest!
   end
end

And so the function is to be used like this now: {{ 'android-icon-36x36.png' | bust_cache: 'assets/favicon' }}

I had to add a condition when it's scss folder, and when the resource is at the root of the project.
I've never coded in rubby, there may be errors, don't hesitate to tell me, but on my side it seems to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment