Search code examples
sinatrahelpermodular

Make Sinatra Helpers available only in some routes (modular application)


I have two different versions of an application that use slightly different versions of some methods.

module Sinatra
  class MyApp < Sinatra::Base
    helpers Sinatra::Version1
    helpers Sinatra::Version2
  end
end

module Sinatra
  module Version1
    def say_hello
      puts "Hello from Version1"
    end
  end
  helpers Version1
end

module Sinatra
  module Version2
    def say_hello
      puts "Hello from Version2"
    end
  end
  helpers Version2
end

I realize that helpers specified this way are "top level" and are made available to all routes.

I would like to have the different versions of the methods available to different routes. Is there some way to accomplish this within a modular application?


Solution

  • It is possible, if you split your application into two different modular classes which "include" the helpers as necessary. For instance:

    # config.ru
    
    require './app.rb'
    
    map('/one') do
      run MyApp1
    end
    
    map('/two') do
      run MyApp2
    end
    
    
    # app.rb
    # helper modules same as you've mentioned above.
    
    class MyApp1 < Sinatra::Base
      helpers Sinatra::Version1
    
      get '/' do
        say_hello
      end
    end
    
    class MyApp2 < Sinatra::Base
      helpers Sinatra::Version2
    
      get '/' do
        say_hello
      end
    end
    

    Whether this is the best way to go about is something I still need to ponder.