1
- require " mimemagic"
1
+ require ' mimemagic'
2
2
require 'json/ext'
3
+ require 'uri'
3
4
4
5
module ImageEncodeCache
5
6
@@cached_base64_codes = Hash . new
@@ -21,41 +22,61 @@ class ImageEncodeTag < Liquid::Tag
21
22
def initialize ( tag_name , var , options )
22
23
split = var . split ( ';' )
23
24
@var = split [ 0 ] . strip
24
- @default = split [ 1 ] . strip
25
+ @default = File . join ( __dir__ , '..' , split [ 1 ] . strip )
26
+
27
+ fetch ( @default )
25
28
super
26
29
end
27
30
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
+
28
48
def render ( context )
29
49
require 'open-uri'
30
50
require 'base64'
31
51
32
52
encoded_image = ''
53
+ url = @default
33
54
34
55
begin
35
56
# https://stackoverflow.com/questions/6672007/how-do-you-access-nested-elements-of-a-hash-with-a-single-string-key
36
57
# 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 ( '.' ) ) || ''
47
59
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
50
65
51
- "data:#{ data_type } ;base64,#{ encoded_image } "
66
+ # Return the Base64 of that URL
67
+ fetch ( url )
52
68
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
53
74
puts e . message
54
- "error!"
75
+ fetch ( @default )
55
76
end
56
77
end
57
78
end
58
79
end
59
80
end
60
81
61
- Liquid ::Template . register_tag ( 'base64' , Jekyll ::Tags ::ImageEncodeTag )
82
+ Liquid ::Template . register_tag ( 'base64' , Jekyll ::Tags ::ImageEncodeTag )
0 commit comments