2013-07-09 13 views
1

問題here詢問如何將Rails視圖幫助函數提取到gem中,並且接受答案非常好。如何在一個可用於Sinatra視圖的gem中創建函數?

我在想 - 如何爲Sinatra做同樣的事情?我正在製作一個gem,它有一堆在模塊中定義的幫助函數,並且我想讓這些函數可用於Sinatra視圖。但無論我嘗試,我似乎無法訪問的功能,我只是得到一個undefined local variable or method錯誤。

到目前爲止,我的寶石結構看起來是這樣的(其他的東西一樣省略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,我有:

我有:
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 

這是行不通的。我哪裏錯了? (如果你想知道,是的,我需要在一個單獨的文件中使用helper函數,我打算使gem與Rails兼容,所以我希望保持函數的隔離/解耦。可能)。

回答

2

你主要只是缺少調用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::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

+0

謝謝。但是我發現我並不需要在'sinatra.rb'中需要'sinatra/base',也不需要'Sinatra.register CoolGem :: Sinatra'。只要在我的應用程序的類中添加'register CoolGem :: Sinatra'似乎就是需要的所有東西...... –

+0

@XåpplI'-I0llwlg'I-是的,如果您已經需要sinatra(例如在您的主應用程序中)噸需要再次。另外'Sinatra.register CoolGem :: Sinatra'將使經典的Sinatra應用程序可用擴展。如果你使用模塊化風格,你也需要在應用程序類中使用'register'。如果您正在製作寶石,您可能需要包含'Sinatra.register CoolGem :: Sinatra',以便它能夠像使用經典風格的人一樣按預期工作。 – matt

+0

啊,我明白了。謝謝你澄清。 –

相關問題