AlexNikolaev94 AlexNikolaev94 - 2 months ago 22
Ruby Question

Undefined method authenticated? form main::Object

I'm learning Sinatra now and I'm building a tiny blog. I've got a little problem with an

authenticated?
method. I've set up authentication, and now I want the rest of my app to be loaded only when the user is authenticated. So, in my
app.rb
I have the following:

helpers do
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end

def authenticated?
redirect '/login' unless current_user
end
end

if authenticated?
# get '/' { ... }
# get '/new' { ... }
# post '/new' { ... }
# the rest of an app (creating, updating and deleting posts go here)
end


When I run the app, it returns me the following error

undefined method authenticated? form main::Object


What have I done wrong?

Answer

According to docs you'd use your authenticated? method as follows:

get '/' do
  if authenticated?
    # something
  else
    # something else
  end
end