sinatra helper in external file

后端 未结 5 1489
半阙折子戏
半阙折子戏 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条回答
  •  孤城傲影
    2021-02-07 07:01

    It seems the answer @DaveSag offered miss something. Should add a line at the beginning of my_modular_app.rb:

    $:.unshift File.expand_path('../lib', __FILE__)  # add ./lib to $LOAD_PATH
    
    require 'sinatra/base'
    require 'sinatra/some_helpers' # this line breaks unless line 1 is added.
    
    # more code below...
    

    In addition, if someone prefers a "classical style" like me, the following is for you :)

    In app.rb

    $:.unshift File.expand_path('../lib', __FILE__)
    
    require 'sinatra'
    require 'sinatra/some_helpers'
    
    get '/' do
      hello_world
    end
    

    In lib/sinatra/some_helpers.rb

    module Sinatra
      module SomeHelper
        def hello_world
          "Hello World from Helper!!"
        end
      end
    
      helpers SomeHelper
    end
    

提交回复
热议问题