Skip to content

Instantly share code, notes, and snippets.

@tardate
Forked from sausheong/rtext.rb
Created January 3, 2012 09:02
Show Gist options
  • Save tardate/1554178 to your computer and use it in GitHub Desktop.
Save tardate/1554178 to your computer and use it in GitHub Desktop.
Random text generator app. Missing the dictionary file as well as the index.html file.
require 'sinatra'
DICTIONARY = File.open("dictionary.txt", 'r').readlines
$books = {}
$bookwords = {}
text_names = %w(holmes1 barsoom1 crusoe)
text_names.each do |name|
$books[name.to_sym] = File.open("#{name}.txt", 'r').readlines.join(" ").split.join(" ").split(". ")
$bookwords[name.to_sym] = File.open("#{name}.txt", 'r').read.downcase.split(/\W+/).uniq
end
get '/' do
File.read(File.join('public', 'index.html'))
end
["/words", "/words/:num"].each do |route|
get route do
num = (params[:num] || 1).to_i
halt 404, {'Content-Type' => 'text/html'}, "Should be a number < #{DICTIONARY.count}!" if num > DICTIONARY.count or num <= 0
DICTIONARY.sample(num).join(" ")
end
end
["/:text/words", "/:text/words/:num"].each do |route|
get route do
num = (params[:num] || 1).to_i
bookwords = $bookwords[params[:text].to_sym]
halt 404, {'Content-Type' => 'text/html'}, "Sorry, I only know about the texts: #{text_names.join(', ')}!" unless bookwords
halt 404, {'Content-Type' => 'text/html'}, "Should be a number < #{bookwords.count}!" if num > bookwords.count or num <= 0
bookwords.sample(num).join(" ")
end
end
["/:text", "/:text/:from", "/:text/:from/:count"].each do |route|
get route do
booklines = $books[params[:text].to_sym]
halt 404, {'Content-Type' => 'text/html'}, "Sorry, I only know about the texts: #{text_names.join(', ')}!" unless booklines
from, count = (params[:from] || rand(booklines.count)).to_i, (params[:count] || 0).to_i
halt 404, {'Content-Type' => 'text/html'}, "From line should be a number < #{booklines.count}!" if from > booklines.count or from <= 0
halt 404, {'Content-Type' => 'text/html'}, "Number of lines should be a number < 100!" if count < 0 or count > 100
booklines[from..from+count].join(". ") + "."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment