Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra: run ruby code when a URL is hit

Tags:

ruby

sinatra

I want to run a script (code.rb) every time the url /code is hit.

How do I run the script?

require 'sinatra'
get '/' do
  #run the script
end
like image 387
donald Avatar asked Jan 17 '11 02:01

donald


2 Answers

Either fork off another process:

system('ruby code.rb')

... or simply load the script into the current context:

load 'code.rb' # *not* require
like image 107
Andy Lindeman Avatar answered Nov 03 '22 00:11

Andy Lindeman


You need to load the code to ensure that it is run each time; require will only load the code once on the first request, and then not again:

smagic:Desktop phrogz$ cat hi.rb
  puts "hi"

smagic:Desktop phrogz$ cat test.rb
  require 'sinatra'
  get '/require' do
    x = require_relative( 'hi.rb' )
    "require sez #{x}"
  end

  get '/load' do
    x = load( 'hi.rb' )
    "load sez #{x}"
  end

smagic:Desktop phrogz$ ruby test.rb 
  == Sinatra/1.1.2 has taken the stage on 4567 for development with backup from Thin
  >> Thin web server (v1.2.7 codename No Hup)
  >> Maximum connections set to 1024
  >> Listening on 0.0.0.0:4567, CTRL+C to stop
  hi
  127.0.0.1 - - [16/Jan/2011 20:49:43] "GET /require HTTP/1.1" 200 16 0.0019
  127.0.0.1 - - [16/Jan/2011 20:49:46] "GET /require HTTP/1.1" 200 17 0.0005
  hi
  127.0.0.1 - - [16/Jan/2011 20:49:52] "GET /load HTTP/1.1" 200 13 0.0009
  hi
  127.0.0.1 - - [16/Jan/2011 20:49:54] "GET /load HTTP/1.1" 200 13 0.0008
  127.0.0.1 - - [16/Jan/2011 20:50:09] "GET /require HTTP/1.1" 200 17 0.0005
  127.0.0.1 - - [16/Jan/2011 20:50:12] "GET /require HTTP/1.1" 200 17 0.0005

The output of hi comes before the request entry in the log; you can see that the requests to 'require' only output hi the first time, while requests to 'load' show hi each time. Here's the output of the server, where true indicates that the code in the file was actually run and false shows that it was not:

smagic:~ phrogz$ curl http://localhost:4567/require
require sez true

smagic:~ phrogz$ curl http://localhost:4567/require
require sez false

smagic:~ phrogz$ curl http://localhost:4567/load
load sez true

smagic:~ phrogz$ curl http://localhost:4567/load
load sez true

smagic:~ phrogz$ curl http://localhost:4567/require
require sez false

smagic:~ phrogz$ curl http://localhost:4567/require
require sez false
like image 20
Phrogz Avatar answered Nov 02 '22 23:11

Phrogz