Created
March 15, 2014 14:15
-
-
Save berkes/9567967 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
require "sinatra" | |
include Math | |
# Anything but a space, number, .+-*/ or ^ is dissallowed | |
WHITELIST = %r{[^ 0-9.+\-*\/\^]+} | |
html = <<-EOT | |
<html> | |
<head> | |
<style> | |
#expression { width: 100%, font-size 3em; display: block; margin-bottom: 1em; } | |
</style> | |
</head> | |
<body> | |
<input id="expression" placeholder="1+2"/> | |
<div id="result"><div> | |
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> | |
<script> | |
$('#expression').keyup(function(){ | |
$.get('/calc',{ | |
exp:$('#expression').val() | |
}, function(r){ | |
$('#result').html(r); | |
}); | |
}); | |
</script> | |
</body></html> | |
EOT | |
get '/' do | |
html | |
end | |
get '/calc' do | |
begin | |
eval(params['exp'].gsub(WHITELIST, '')).to_s | |
rescue | |
'Invalid expression' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment