Jessie Scinor
Jessie Scinor

Reputation: 39

How to generate and then redirect to that generated link in Sinatra?

I have some troubles. Here is my code:

get '/generate' do
  @link = Link.create(url: Helpers.random, message: "my new ffffff")
  session[:test] = @link.url
  redirect ("/message/#{session[:test]}")
end

get "/message/#{session[:test]}" do
  erb :buttons
end

In first method I generate some link, and in second I want to redirect to that generated link. How could I do it easy? Because I receive

Sinatra doesn’t know this ditty.

Even if I take away session[:test] = @link.url from get method to separate method I receive:

NameError: undefined local variable or method `session' for main:Object

Upvotes: 1

Views: 212

Answers (1)

max pleaner
max pleaner

Reputation: 26778

There are 2 "scopes" here and you're mixing them in a way that's not possible.

get "/message/#{session[:test]}" do

^^ this is run when the app starts up, it is never re-run. The content inside the block could be run multiple times, but not the route matcher.

The way to handle this is to change the route matcher to accept a URL param:

get "/message/:some_var"

Then in the block refer to params[:some_var].

Upvotes: 1

Related Questions