Skip to content

Instantly share code, notes, and snippets.

@virtualstaticvoid
Last active March 19, 2018 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virtualstaticvoid/9bf2653a554e0381aeb927847518d455 to your computer and use it in GitHub Desktop.
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
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