【发布时间】:2011-08-02 18:16:16
【问题描述】:
我的主要 Sinatra project_name.rb 中有很多助手,我想将它们删除到外部文件中,这样做的最佳做法是什么?
来自 ./preject_name.rb
helpers do
...#bunch of helpers
end
例如 ./helpers/something.rb
谢谢你
【问题讨论】:
标签: sinatra
我的主要 Sinatra project_name.rb 中有很多助手,我想将它们删除到外部文件中,这样做的最佳做法是什么?
来自 ./preject_name.rb
helpers do
...#bunch of helpers
end
例如 ./helpers/something.rb
谢谢你
【问题讨论】:
标签: sinatra
简单推荐的方法:
module ApplicationHelper
# methods
end
class Main < Sinatra::Base
helpers ApplicationHelper
end
【讨论】:
唉,如果您像我一样构建一个模块化 Sinatra 应用程序,它比简单地将helpers 移出另一个文件要复杂一些。
我让它工作的唯一方法如下。
首先在你的应用程序中(我会称之为my_modular_app.rb)
require 'sinatra/base'
require 'sinatra/some_helpers'
class MyModularApp < Sinatra::Base
helpers Sinatra::SomeHelpers
...
end
然后创建文件夹结构./lib/sinatra/并创建some_helpers.rb如下:
require 'sinatra/base'
module Sinatra
module SomeHelpers
def help_me_world
logger.debug "hello from a helper"
end
end
helpers SomeHelpers
end
这样做,您可以简单地将所有助手拆分为多个文件,从而在更大的项目中提供更高的清晰度。
【讨论】:
正如你自己所说:
将helpers 块移动到另一个文件中,并将require 移动到您需要的位置。
#helpers.rb
helpers do
...
end
#project_name.rb
require 'path/to/helpers.rb'
【讨论】:
require "#{File.dirname(__FILE__)}/helpers/helpers.rb"
require_relative 'helpers/helpers' 而不是 File-construct
@DaveSag 提供的答案似乎漏掉了一些东西。应该在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...
另外,如果有人像我一样喜欢“古典风格”,以下是给你的:)
在app.rb
$:.unshift File.expand_path('../lib', __FILE__)
require 'sinatra'
require 'sinatra/some_helpers'
get '/' do
hello_world
end
在 lib/sinatra/some_helpers.rb
module Sinatra
module SomeHelper
def hello_world
"Hello World from Helper!!"
end
end
helpers SomeHelper
end
【讨论】:
我刚刚将require_relative './lib/sinatra/helpers' 添加到我的config.ru 中,仅此而已。
所以它看起来像这样:
require_relative './config/environment'
require_relative './lib/sinatra/helpers'
use ProjectsController
run ApplicationController
我的./lib/sinatra/helpers.rb 文件甚至不是一个模块,我没有使用任何要求或包含在其中。我可以直接在这个文件中定义方法并在整个应用程序中使用它们。
@kgpdeveloper 的答案对我不起作用。
【讨论】: