sinatra helper in external file

Just as you said it yourself:

Move the helpers block into another file and require it where you need.

#helpers.rb
helpers do
...
end

#project_name.rb
require 'path/to/helpers.rb'

Alas, if, like me, you are building a modular Sinatra app, it's a little more complex than simply moving the helpers out into another file.

The only way I got this to work is as follows.

first up in your app (I'll call this my_modular_app.rb)

require 'sinatra/base'
require 'sinatra/some_helpers'

class MyModularApp < Sinatra::Base
  helpers Sinatra::SomeHelpers

  ...

end

and then create the folder structure ./lib/sinatra/ and create some_helpers.rb as follows:

require 'sinatra/base'

module Sinatra
  module SomeHelpers

    def help_me_world
      logger.debug "hello from a helper"
    end

  end

  helpers SomeHelpers

end

doing this you can simply split all your helpers up into multiple files, affording more clarity in larger projects.


The simple and recommended way:

module ApplicationHelper

# methods

end

class Main < Sinatra::Base

  helpers ApplicationHelper

end

Tags:

Sinatra