tags:

views:

522

answers:

4

I don't know if this is a ruby question or a Sinatra question, because I'm new to both. The following code does not work, and I understand why, because the first my_variable is local to its block. I just don't know the syntax for getting it right.

require 'rubygems'
require 'sinatra'

configure do
    my_variable = "world"
end

get '/' do
    "Hello " + my_variable
end

EDIT1 - the following works, but then I guess I'm confused about the proper purpose of the configure block.

require 'rubygems'
require 'sinatra'

my_variable = "world"

get '/' do
    "Hello " + my_variable
end
+6  A: 
require 'rubygems'
require 'sinatra'

set :my_variable, "world"

get '/' do
  "Hello " + options.my_variable
end
Simone Carletti
I guess, I'm confused about the purpose of a Sinatra config block versus doing something outside of a block.
Corey Trager
Options are application level settings while configuration allows you to customize the behavior according to current environment.
Simone Carletti
configure is just a block of code which will be executed once.
Yoann Le Touche
+1  A: 

One other way is :

require 'rubygems'
require 'sinatra'

@my_variable="world"

get '/' do
  "Hello " + @my_variable
end
Yoann Le Touche
A: 

I would set a class variable — eg. @@my_variable — inside the configure block. The configure block exists for code you want to run at start up, so setting your variable their makes sense. Your Sinatra application is a subclass of Sinatra::Base, so using a class variable in this situation seems appropriate.

funkaoshi
A: 

how do i do a PUT in sinatra?

JSON
Make a new question instead of trying to revive an old one.
theIV