jdkealy
jdkealy

Reputation: 4907

Modular Sinatra App using Sinatra Reloader?

Hi if I had a 'main' sinatra file with the following code,

require 'sinatra'
require "sinatra/reloader"

class MyApp < Sinatra::Base
  configure do
    require "./rest/auth.rb"
    register Sinatra::Reloader
    also_reload '/rest/auth'
  end

  get '/' do
    erb :home
  end
end

And I wanted to put my authentication logic inside of /rest/auth.rb, how can I get /rest/auth.rb to reload in development mode? Must I put the configure block and require sinatra/reloader in every one of my controller files? I'd like for my controllers to inherit the settings of my main class. The code inside of auth.rb is as follows:

class MyApp < Sinatra::Base
  set(:auth) do |*roles|  # <- notice the splat here
    condition do
      unless logged_in?
        session[:success_url] = request.path_info
        redirect '/'
      end
    end
  end

  def logged_in?
    current_user
  end

  def current_user
    if session[:user_id]
      u = User.find(:id=>"#{session[:user_id]}")
    else
      false
    end
  end
end

I need to restart the server for my changes to take place but I can throw that reload code in auth.rb's configure block though I wouldn't like to. Any ideas?

Upvotes: 2

Views: 1053

Answers (1)

Shtirlic
Shtirlic

Reputation: 692

Try to rewrite like this

require 'sinatra/base'
require "sinatra/reloader"

class MyApp < Sinatra::Base

  configure :development do
    register Sinatra::Reloader
    also_reload './rest/auth'
  end

  require "./rest/auth.rb"


  get '/' do
    erb :home
  end

end

Upvotes: 9

Related Questions