2021-12-26 09:59:48 -08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-01-17 16:05:42 -08:00
|
|
|
# Generates some questions.
|
2014-12-08 15:59:33 -08:00
|
|
|
module QuestionGenerator
|
2015-01-17 16:05:42 -08:00
|
|
|
# Version of QuestionGenerator
|
2023-02-14 23:25:37 -08:00
|
|
|
VERSION = "1.2.0"
|
2014-12-08 15:59:33 -08:00
|
|
|
|
|
|
|
class << self
|
2015-01-17 16:05:42 -08:00
|
|
|
# The base path to the questions (e.g. +'/home/nilsding/questions'+).
|
2023-01-31 13:57:44 -08:00
|
|
|
attr_reader :question_base_path
|
2015-01-17 16:05:42 -08:00
|
|
|
# The default locale, as a symbol.
|
2014-12-08 15:59:33 -08:00
|
|
|
attr_accessor :default_locale
|
|
|
|
end
|
|
|
|
|
2023-01-31 13:57:44 -08:00
|
|
|
module_function
|
|
|
|
|
2015-01-17 16:05:42 -08:00
|
|
|
# Generates a new question.
|
|
|
|
# @param options [Hash] A customizable set of options.
|
2023-01-31 13:57:44 -08:00
|
|
|
# @param :locale [Symbol] The target locale
|
|
|
|
# @param :prefix [String] Prefix of the question, e.g. +'¿'+
|
|
|
|
# @param :suffix [String] Suffix of the question, e.g. +' ?'+
|
2015-01-17 16:05:42 -08:00
|
|
|
# @return [String] String containing the generated question.
|
2023-01-31 13:57:44 -08:00
|
|
|
def generate(locale: @default_locale, prefix: "", suffix: "?")
|
|
|
|
compile(locale:) unless @compiled.key?(locale)
|
|
|
|
|
|
|
|
prefix + @compiled[locale].sample + suffix
|
2014-12-08 15:59:33 -08:00
|
|
|
end
|
2015-01-17 16:05:42 -08:00
|
|
|
|
|
|
|
# Compiles all the questions and stores it into the +@compiled+ hash.
|
2023-01-31 13:57:44 -08:00
|
|
|
# @param :locale [Symbol] The target locale
|
|
|
|
def compile(locale: @default_locale)
|
2023-02-14 23:25:37 -08:00
|
|
|
@compiled[locale] = File.readlines(
|
|
|
|
File.expand_path("#{locale}.txt", @question_base_path),
|
|
|
|
chomp: true,
|
|
|
|
)
|
2023-01-31 13:57:44 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
def question_base_path=(path)
|
|
|
|
raise Errno::ENOENT.new(path) unless Dir.exist?(path)
|
|
|
|
|
|
|
|
@compiled = {} # new dir, force a recompile
|
|
|
|
@question_base_path = path
|
2014-12-08 15:59:33 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2023-01-31 13:57:44 -08:00
|
|
|
module_function
|
|
|
|
|
|
|
|
@question_base_path = File.expand_path("./questions/", __dir__)
|
|
|
|
@default_locale = :en
|
|
|
|
@compiled = {}
|
2014-12-08 15:59:33 -08:00
|
|
|
end
|