forked from Nerds/NerdPursuit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
creator
executable file
·71 lines (55 loc) · 1.79 KB
/
creator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require 'json'
category = ARGV.shift
# Helper method, idea stolen from higline
def ask(prompt)
print prompt
gets.chomp
end
# Helper method for exiting the program with a status code of 1 and a message
def die(message)
puts message
exit 1
end
die("No category given! Run creator with ./creator [category]") if !category or category.empty?
die("No such category. Create a '#{category}' folder in questions to add it.") if !File.exists?("questions/#{category}")
question = ask("New question for #{category}: ")
correct_answer = ask("Correct answer: ")
# Get all wrong answers
iterator = 0
answers = [correct_answer]
begin
iterator += 1
wrong_answer = ask("Wrong answer ##{iterator} (leave empty to continue): ")
answers.push wrong_answer if wrong_answer != ''
end while wrong_answer != '' and iterator < 3
level = ask("Nerd level (1-5): ").to_i
# Handle edge cases
level = 5 if level > 5
level = 1 if level < 1
# Extract the creator from git
creator = `git config --get user.name`.chomp
# Shuffle the answers and find the index of the correct one
answers.shuffle!
correct_index = answers.index(correct_answer)
# Construct the hash that will be converted to JSON
data = {
:id => '',
:category => category,
:nerd_level => level,
:text => question,
:created_by => creator,
:created_at => Time.now.strftime('%Y-%m-%d'),
:right_answer => "a#{correct_index + 1}"
}
# Add the answers to the result hash
answers.each_with_index do |answer, index|
data["a#{index+1}"] = answer
end
json = JSON.pretty_generate({ :question => data })
filename = question.downcase[0..30].gsub(/[^a-z0-9]+/i, '_').sub(/_+$/, '') + '.json'
File.open("questions/#{category}/#{filename}", "w") do |file|
file.write(json)
end unless filename == '.json'