【问题标题】:NoMethodError Sinatra Modular appNoMethodError Sinatra 模块化应用程序
【发布时间】:2013-06-19 12:41:36
【问题描述】:

可能是一些非常基本的东西,但我希望能够在模块化 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

我的问题是我在个人资料课程之外需要它。这是没有意义的,因为我要求我的 ENV 变量的配置文件以相同的方式被读取,但它们又不是方法,所以我想这确实有意义。

我想我可能很难理解模块化应用程序是什么,而不是使用经典风格的 sinatra 应用程序。

任何指针表示赞赏

错误信息

NoMethodError at / undefined method `aws_asset' for #<Profile:0x007f1e6c4905c0> file: index.erb location: block in singletonclass line: 8

【问题讨论】:

  • 你真的错过了require 行末尾的撇号吗?您收到的实际完整错误消息是什么?
  • 不,那是一个错字,已经修改,我也添加了我得到的错误

标签: ruby methods sinatra helper


【解决方案1】:

当您像这样在顶层使用 helpers do ... 时,您会将方法作为助手添加到 Sinatra::Application不是您的 Profile 类。如果您只使用 Sinatra 模块化样式,请确保您只使用 require 'sinatra/base',而不是 require sinatra,这将防止您像这样混淆这两种样式。

在这种情况下,您可能应该为您的助手创建一个模块,而不是使用helpers do ...,然后在您的Profile 类中添加带有helpers method 的模块。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多