簡體   English   中英

如何使gem中的功能可用於Sinatra視圖?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM