Skip to content
This repository was archived by the owner on Sep 27, 2018. It is now read-only.

Commit 3c977eb

Browse files
author
lepon01
committed
Use default image on error
1 parent 82458ac commit 3c977eb

File tree

1 file changed

+38
-17
lines changed

1 file changed

+38
-17
lines changed

lib/jekyll_image_encode.rb

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
require "mimemagic"
1+
require 'mimemagic'
22
require 'json/ext'
3+
require 'uri'
34

45
module ImageEncodeCache
56
@@cached_base64_codes = Hash.new
@@ -21,41 +22,61 @@ class ImageEncodeTag < Liquid::Tag
2122
def initialize(tag_name, var, options)
2223
split = var.split(';')
2324
@var = split[0].strip
24-
@default = split[1].strip
25+
@default = File.join(__dir__, '..', split[1].strip)
26+
27+
fetch(@default)
2528
super
2629
end
2730

31+
def fetch(url)
32+
image_handle = open(url)
33+
34+
if self.cached_base64_codes.has_key? url
35+
encoded_image = self.cached_base64_codes[url]
36+
else
37+
# p "Caching #{@url} as local base64 string ..."
38+
encoded_image = Base64.strict_encode64(image_handle.read)
39+
self.cached_base64_codes.merge!(url => encoded_image)
40+
end
41+
42+
data_type = MimeMagic.by_magic(image_handle)
43+
image_handle.close
44+
45+
"data:#{data_type};base64,#{encoded_image}"
46+
end
47+
2848
def render(context)
2949
require 'open-uri'
3050
require 'base64'
3151

3252
encoded_image = ''
53+
url = @default
3354

3455
begin
3556
# https://stackoverflow.com/questions/6672007/how-do-you-access-nested-elements-of-a-hash-with-a-single-string-key
3657
# Splat and dig, is the answer
37-
url = context.registers[:page].dig(*@var.split('.')) || File.join(__dir__, '..', @default)
38-
image_handle = open(url)
39-
40-
if self.cached_base64_codes.has_key? url
41-
encoded_image = self.cached_base64_codes[url]
42-
else
43-
# p "Caching #{@url} as local base64 string ..."
44-
encoded_image = Base64.strict_encode64(image_handle.read)
45-
self.cached_base64_codes.merge!(url => encoded_image)
46-
end
58+
userlink = context.registers[:page].dig(*@var.split('.')) || ''
4759

48-
data_type = MimeMagic.by_magic(image_handle)
49-
image_handle.close
60+
# If the userlink is HTTP or HTTPS, set the URL to that link
61+
if ['http', 'https'].include?URI.parse(userlink).scheme
62+
puts userlink
63+
url = userlink
64+
end
5065

51-
"data:#{data_type};base64,#{encoded_image}"
66+
# Return the Base64 of that URL
67+
fetch(url)
5268
rescue OpenURI::HTTPError => e
69+
# If an error occured, return the default
70+
puts e.message
71+
fetch(@default)
72+
rescue URI::InvalidURIError => e
73+
# If the URI was invalid, return the default
5374
puts e.message
54-
"error!"
75+
fetch(@default)
5576
end
5677
end
5778
end
5879
end
5980
end
6081

61-
Liquid::Template.register_tag('base64', Jekyll::Tags::ImageEncodeTag)
82+
Liquid::Template.register_tag('base64', Jekyll::Tags::ImageEncodeTag)

0 commit comments

Comments
 (0)