sinatra helper in external file

左心房为你撑大大i 提交于 2020-01-01 02:28:07

问题


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_name.rb

   helpers do
     ...#bunch of helpers
   end

to for exapmple ./helpers/something.rb

thank you


回答1:


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'



回答2:


The simple and recommended way:

module ApplicationHelper

# methods

end

class Main < Sinatra::Base

  helpers ApplicationHelper

end



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/6916626/sinatra-helper-in-external-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!