Reputation: 1119
What is the best way to assign variables in sinatra that can be used on all views(all erb files).
I know it can be done using global variables in the main file lets say app.rb but is there a better way to do it without using global variables? eg in app.rb, i can do:
@@a = "hello"
get '/' do
erb :index
end
get '/hi' do
erb :page
end
and in index.erb and page.erb files:
<%= @@a %>
But is there a way to do so without using global variables or is global variables the best way to go about doing that?
Upvotes: 2
Views: 1063
Reputation: 3839
Session variables are usually used for cross view access. In sinatra, it's just your standard hash:
session[:whatever] = "Hello"
And that can be accessed anywhere once set. It will persist independently per user session.
For example, a common helper I use is:
# set session[:user] = user's ID when they log in
def user
@user ||= User.get(session[:user])
end
You'd access that in your views or controllers using user
.
Upvotes: 1
Reputation: 59611
Create a module with constants of all the strings/variables you want accessible. All views will have access to your modules:
module StringConstants
LOGIN_PAGE = "Welcome to X"
LOGOUT = "See you again soon"
end
then in your views:
<%= StringConstants::LOGIN_PAGE %>
Upvotes: 1