Class: Jekyll::GenerateTags::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll-generate-tags/generator.rb

Constant Summary collapse

@@hash_key =
"cache-key"
@@cache_folder_name =
".tags-cache"
@@tag_options_name =
"tag_options.txt"
@@default_confidence =
".50"

Instance Method Summary collapse

Instance Method Details

#create_cache_folderObject



71
72
73
74
75
76
77
78
# File 'lib/jekyll-generate-tags/generator.rb', line 71

def create_cache_folder()
  cache_folder_path = File.expand_path(@@cache_folder_name)
  # Check if the folder exists
  if !Dir.exists?(cache_folder_path)
    # Create the folder
    FileUtils.mkdir_p(cache_folder_path)
  end
end

#generate_tags(content, tags, confidence) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jekyll-generate-tags/generator.rb', line 18

def generate_tags(content, tags, confidence)
  # Do tags exist in `_config.yml`?
  if tags.nil?
    # Look for tags in project root
    tags_path = File.expand_path(@@tag_options_name)
    if !File.exists?(tags_path)
      # Use default tags from gem
      tags_path = File.expand_path(@@tag_options_name, __dir__)
    end
    tags_file = File.read(tags_path)
    lines = tags_file.split("\n")
    tags = lines.join(",")
  end

  if confidence.nil?
    confidence = @@default_confidence
  end

  cache_key = content + tags + String(confidence)

  result = self.get_cache(cache_key)
  if result.nil?
    script_path = File.expand_path("generate.py", __dir__)
    arg1 = Shellwords.escape(content)
    arg2 = Shellwords.escape(tags)
    arg3 = Shellwords.escape(String(confidence))
    result = `python #{script_path} #{arg1} #{arg2} #{arg3}`

    self.set_cache(cache_key, result)
  end

  result
end

#get_cache(key) ⇒ Object

Retrieves existing generated tags from a cache file for fast reuse



62
63
64
65
66
67
68
69
# File 'lib/jekyll-generate-tags/generator.rb', line 62

def get_cache(key)
  cache_path = get_cache_file_path(key)
  # Retrieve value from file
  if File.exists?(cache_path)
    result = File.read(cache_path)
    result
  end
end

#get_cache_file_path(key) ⇒ Object



80
81
82
83
84
85
86
87
# File 'lib/jekyll-generate-tags/generator.rb', line 80

def get_cache_file_path(key)
  create_cache_folder()

  # Create the HMAC
  hmac = OpenSSL::HMAC.hexdigest('sha256', @@hash_key, key)
  cache_path = File.expand_path("#{@@cache_folder_name}/#{hmac}.txt")
  cache_path
end

#set_cache(key, value) ⇒ Object

Stores newly generated tags in a file for fast reuse



53
54
55
56
57
58
59
# File 'lib/jekyll-generate-tags/generator.rb', line 53

def set_cache(key, value)
  cache_path = get_cache_file_path(key)
  # Store file
  File.open(cache_path, "w") do |file|
    file.puts(value)
  end
end