sinatra helper in external file

后端 未结 5 1488
半阙折子戏
半阙折子戏 2021-02-07 06:48

I have lot of helpers in my main Sinatra project_name.rb and I want to remove them to the external file, what is the best practice to do that ?

from ./preject_na

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 07:06

    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.

提交回复
热议问题