questiongenerator/lib/questiongenerator.rb

53 lines
1.4 KiB
Ruby
Raw Permalink Normal View History

# frozen_string_literal: true
# Generates some questions.
2014-12-08 15:59:33 -08:00
module QuestionGenerator
# 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
# The base path to the questions (e.g. +'/home/nilsding/questions'+).
attr_reader :question_base_path
# The default locale, as a symbol.
2014-12-08 15:59:33 -08:00
attr_accessor :default_locale
end
module_function
# Generates a new question.
# @param options [Hash] A customizable set of options.
# @param :locale [Symbol] The target locale
# @param :prefix [String] Prefix of the question, e.g. +'¿'+
# @param :suffix [String] Suffix of the question, e.g. +' ?'+
# @return [String] String containing the generated question.
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
# Compiles all the questions and stores it into the +@compiled+ hash.
# @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,
)
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
module_function
@question_base_path = File.expand_path("./questions/", __dir__)
@default_locale = :en
@compiled = {}
2014-12-08 15:59:33 -08:00
end