Created
November 16, 2011 08:52
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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