Skip to content

Instantly share code, notes, and snippets.

@sausheong
Created November 16, 2011 08:52
Show Gist options
  • Save sausheong/1369611 to your computer and use it in GitHub Desktop.
Save sausheong/1369611 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 = {}
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(". ")
end
get '/' do
File.read(File.join('public', 'index.html'))
end
["/:text", "/:text/:from", "/:text/:from/:count"].each do |route|
get route do
to_use = params[:text].to_sym
pass unless $books.keys.include? to_use
from, count = (params[:from] || rand($books[to_use].count)).to_i, (params[:count] || 0).to_i
halt 404, {'Content-Type' => 'text/html'}, "From line should be a number < #{$books[to_use].count}!" if from > $books[to_use].count or from <= 0
halt 404, {'Content-Type' => 'text/html'}, "Number of lines should be a number < 100!" if count < 0 or count > 100
$books[to_use][from..from+count].join(". ") + "."
end
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
words = []
num.times { words << DICTIONARY[rand(DICTIONARY.count)].chomp }
words.join(" ")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment