【问题标题】:How do I make functions in a gem available to Sinatra views?如何使 gem 中的函数对 Sinatra 视图可用?
【发布时间】:2013-07-07 08:50:18
【问题描述】:

问题here问如何将Rails view helper函数提取到gem中,accept的回答还不错。

我想知道 - 如何为 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 兼容,所以我想尽可能保持函数的隔离/解耦)。

【问题讨论】:

    标签: ruby-on-rails ruby gem sinatra


    【解决方案1】:

    您主要只是错过了对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 应用程序都可以使用助手。如果您使用模块化样式,您还需要在 Sinatra::Base 子类中调用 register CoolGem::Sinatra。

    在这种情况下,如果您只是提供一些辅助方法,更简单的方法可能是使用 helpers 方法(同样在 cool_gem/sinatra.rb 中):

    require 'sinatra/base'
    require 'cool_gem/helper_functions'
    
    Sinatra.helpers CoolGem::HelperFunctions
    

    现在这些方法将在经典风格的应用程序中可用,而模块化风格的应用程序将需要调用 helpers CoolGem::HelperFunctions。这有点简单,但如果您要向 DSL 上下文添加方法,您将需要使用registered,如上。

    【讨论】:

    • 谢谢。但是我发现sinatra.rb中不需要require 'sinatra/base,也不需要Sinatra.register CoolGem::Sinatra。只需将register CoolGem::Sinatra 添加到我的应用程序的类中似乎就足够了...
    • @XåpplI'-I0llwlg'I- 是的,如果您已经需要 sinatra(例如,在您的主应用程序中),您将不需要再次使用。此外,Sinatra.register CoolGem::Sinatra 将使这些扩展在经典的 Sinatra 应用程序中可用。如果您使用模块化样式,您还需要在您的应用程序类中使用register。如果您要让 gem 可用,您可能需要包含 Sinatra.register CoolGem::Sinatra 以便它可以按预期为使用经典样式的人工作。
    • 啊,我明白了。谢谢你的澄清。
    猜你喜欢
    • 1970-01-01
    • 2012-09-24
    • 2013-12-03
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多