How to make modular helper in Sinatra How to make modular helper in Sinatra ruby ruby

How to make modular helper in Sinatra


You can use a different convention for the helpers method.

module UserSession  def logged_in?   not session[:email].nil?  end  def logout!    session[:email] = nil  endendhelpers UserSessionget '/foo' do  if logged_in?    'Hello you!'  else    'Do I know you?'  endend

The module definition can of course be in another (required) file.

Behind the scenes, helpers <Module> is doing an include, but not simply into the Sinatra application sub-class you are using for your app. The include needs to be made compatible with how get, post etc work their magic, and helpers does that for you.


nevermind, i found the answer, i have tried define_method('UserSession.logged_in?') also, but no luck

last thing i've tried is:

# outside helpersclass UserSession  @@session = nil  def initialize session    @@session ||= session  end  def self.check    throw('must be initialized first') if @@session.nil?  end  def self.logged_in?    self.check    not @@session[:email].nil?  end  def self.logout    self.check    @@session.delete :email  endend

but something must be called first

before // do  UserSession.new sessionend

then it can be used as desired:

get '/' do  if UserSession.logged_in?    # do something here  endend