[英]How do I make functions in a gem available to Sinatra views?
这里的问题询问如何将Rails视图助手功能提取到gem中,接受答案是非常好的。
我想知道-对于Sinatra怎么做? 我正在制作一个在模块中定义了许多辅助函数的gem,我想使这些函数可用于Sinatra视图。 但是无论我如何尝试,我似乎都无法访问这些函数,只是得到了undefined local variable or method
错误。
到目前为止,我的gem结构看起来像这样(其他诸如gemspec之类的东西省略了):
cool_gem/
lib/
cool_gem/
helper_functions.rb
sinatra.rb
cool_gem.rb
在cool_gem.rb
,我有:
if defined?(Sinatra) and Sinatra.respond_to? :register
require 'cool_gem/sinatra'
end
在helper_functions.rb
,我有:
module CoolGem
module HelperFunctions
def heading_tag(text)
"<h1>#{text}</h1>"
end
# + many more functions
end
end
在sinatra.rb
,我有:
require 'cool_gem/helper_functions'
module CoolGem
module Sinatra
module MyHelpers
include CoolGem::HelperFunctions
end
def self.registered(app)
app.helpers MyHelpers
end
end
end
这行不通。 我要去哪里错了?
(而且,如果您想知道,是的,我需要在单独的文件中添加辅助函数。我还计划使gem与Rails兼容,因此,如果可能的话,我希望将这些函数隔离/解耦)。
您主要只是错过了对Sinatra.register
的调用(在cool_gem/sinatra.rb
):
require 'sinatra/base'
require 'cool_gem/helper_functions'
module CoolGem
# you could just put this directly in the CoolGem module if you wanted,
# rather than have a Sinatra sub-module
module Sinatra
def self.registered(app)
#no need to create another module here
app.helpers CoolGem::HelperFunctions
end
end
end
# this is what you're missing:
Sinatra.register CoolGem::Sinatra
现在,任何需要cool_gem
经典风格的Sinatra应用程序cool_gem
将提供帮助器。 如果您使用模块化样式,则还需要在Sinatra::Base
子类中调用register CoolGem::Sinatra
。
在这种情况下,如果您仅提供一些辅助方法, cool_gem/sinatra.rb
简单的方法可能是仅使用helpers
方法(同样在cool_gem/sinatra.rb
):
require 'sinatra/base'
require 'cool_gem/helper_functions'
Sinatra.helpers CoolGem::HelperFunctions
现在,这些方法将在经典样式的应用程序中可用,而模块化样式的应用程序将需要调用helpers CoolGem::HelperFunctions
。 这有点简单,但是如果要将方法添加到DSL上下文中,则需要使用上述registered
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.