Skip to content

Instantly share code, notes, and snippets.

@berkes
Created March 15, 2014 14:15
Show Gist options
  • Save berkes/9567967 to your computer and use it in GitHub Desktop.
Save berkes/9567967 to your computer and use it in GitHub Desktop.
#!/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