donald
donald

Reputation: 23747

Sinatra: run ruby code when a URL is hit

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

Upvotes: 5

Views: 2834

Answers (2)

Andy Lindeman
Andy Lindeman

Reputation: 12165

Either fork off another process:

system('ruby code.rb')

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

load 'code.rb' # *not* require

Upvotes: 8

Phrogz
Phrogz

Reputation: 303361

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

Upvotes: 6

Related Questions