Module: LoremTolkien

Defined in:
lib/lorem_tolkien.rb,
lib/lorem_tolkien/version.rb

Constant Summary collapse

QUOTES_PATH =
File.expand_path("lorem_tolkien/quotes.yml", __dir__)
RAW_QUOTES =
YAML.load_file(QUOTES_PATH)["quotes"]
QUOTES =

Flatten all quotes for legacy/random use

RAW_QUOTES.values.flatten
VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.character_namesObject

New: List all available characters



82
83
84
# File 'lib/lorem_tolkien.rb', line 82

def self.character_names
  RAW_QUOTES.keys
end

.characters(n = 50) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/lorem_tolkien.rb', line 53

def self.characters(n=50)
  # Generate text with exactly n characters from Tolkien quotes
  return "" if n <= 0
  all_text = ""
  QUOTES.each { |quote| all_text += quote + " " }
  if all_text.length < n
    cycles = (n.to_f / all_text.length).ceil
    all_text = all_text * cycles
  end
  result = all_text[0, n]
  if n >= 10 && result.length == n && result[-1] =~ /[\w]/
    last_space = result.rindex(" ")
    if last_space && last_space > n * 0.5
      result = result[0, last_space]
      result += all_text[result.length, n - result.length] if result.length < n
    end
  end
  result[0, n]
end

.paragraphObject



23
24
25
26
27
# File 'lib/lorem_tolkien.rb', line 23

def self.paragraph
  # Generate a paragraph with 3-5 sentences
  sentence_count = rand(3..5)
  sentences(sentence_count).strip
end

.paragraphs(n = 3) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/lorem_tolkien.rb', line 29

def self.paragraphs(n=3)
  paragraphs = []
  n.times do
    paragraphs << paragraph
  end
  paragraphs.join("\n\n")
end

.quote(character) ⇒ Object

New: Get a random quote from a specific character



74
75
76
77
78
79
# File 'lib/lorem_tolkien.rb', line 74

def self.quote(character)
  char = character.to_s
  return nil unless RAW_QUOTES.key?(char)
  quotes = RAW_QUOTES[char]
  quotes[rand(0..(quotes.length - 1))]
end

.sentenceObject



11
12
13
# File 'lib/lorem_tolkien.rb', line 11

def self.sentence
  QUOTES[rand(0..(QUOTES.length - 1))]
end

.sentences(n = 5) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/lorem_tolkien.rb', line 15

def self.sentences(n=5)
  temp = ""
  n.times do |x|
    temp += QUOTES[x % QUOTES.length] + " "
  end
  return temp
end

.words(n = 10) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/lorem_tolkien.rb', line 37

def self.words(n=10)
  # Generate exactly n words from Tolkien quotes
  return "" if n <= 0
  all_words = []
  QUOTES.each do |quote|
    words = quote.split(/\s+/)
    all_words.concat(words)
  end
  if all_words.length < n
    cycles = (n.to_f / all_words.length).ceil
    all_words = all_words * cycles
  end
  selected_words = all_words.shuffle.first(n)
  selected_words.join(" ")
end