[英]NoMethodError Sinatra Modular app
可能是很基本的東西,但是我希望能夠在模塊化Sinatra應用程序中使用一些自定義幫助方法。 我在./helpers/aws_helper.rb中有以下內容
helpers do
def aws_asset( path )
File.join settings.asset_host, path
end
end
然后我認為我希望能夠像這樣使用這種方法
<%= image_tag(aws_asset('/assets/images/wd.png')) %>
但是我得到了上面的區域,所以在我的app.rb文件中
require './helpers/aws_helper'
class Profile < Sinatra::Base
get '/' do
erb :index
end
end
所以我的問題是我在Profile類之外需要它。 這沒有意義,因為我以相同的方式要求ENV變量使用我的配置文件並且正在讀取它們,但是然后它們又不是方法,因此我想這確實有意義。
我認為與使用經典樣式的sinatra應用程序相反,也許我不太想了解模塊化應用程序是什么。
任何指針贊賞
錯誤信息
NoMethodError at / undefined method `aws_asset' for #<Profile:0x007f1e6c4905c0> file: index.erb location: block in singletonclass line: 8
當您使用諸如此類的頂層helpers do ...
時,您helpers do ...
方法作為輔助方法添加到Sinatra::Application
而不是您的Profile
類。 如果您僅使用Sinatra模塊化樣式,請確保僅使用require 'sinatra/base'
而不使用require sinatra
,這將防止您將這兩種樣式require sinatra
。
在這種情況下,您可能應該為您的助手創建一個模塊,而不是使用helpers do ...
,然后在Profile
類中使用helpers
方法添加該模塊。
在helpers/aws_helper.rb
:
module MyHelpers # choose a better name of course
def aws_asset( path )
File.join settings.asset_host, path
end
end
在app.rb
:
class Profile < Sinatra::Base
helpers MyHelpers # include your helpers here
get '/' do
erb :index
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.