Last active
March 19, 2018 21:39
-
-
Save virtualstaticvoid/9bf2653a554e0381aeb927847518d455 to your computer and use it in GitHub Desktop.
Heroku Buildpack R - Serving a plotted image via a Ruby Sinatra web application
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' | |
require 'rinruby' | |
# root page | |
get '/' do | |
sample_size = 10 | |
html = "<html>" | |
html += "<head><title>R Code Test</title></head>" | |
html += "<body>" | |
html += "<p>Running R code...</p>" | |
begin | |
R.eval "x <- rnorm(#{sample_size})" | |
R.eval "sdx <- sd(x)" | |
html += "<p>Succeeded running R code</p>" | |
html += "<pre>x = #{R.x}</pre>" | |
html += "<pre>sd(x) = #{R.sdx}</pre>" | |
# this image is provided by the plot.png get action below | |
html += "<img src=\"plot.png\"></img>" | |
rescue => e | |
html += "<p>Failed running R code...</p>" | |
html += "<p>#{e.message}</p>" | |
end | |
html += "</html>" | |
end | |
get '/plot.png' do | |
# create a temp file for the plot image | |
file = Tempfile.new('plot') | |
# interpolate file name into the R code and run it | |
code = <<-RCODE | |
png("#{file.path}", type="cairo") | |
plot(1:5,1:5) | |
dev.off() | |
RCODE | |
R.eval(code) | |
# response, set type to png | |
send_file file.path, :type => :png | |
# clean up | |
file.close | |
file.unlink | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment