4

我有一个 sinatra 应用程序,它执行黄瓜测试并发送带有结果的电子邮件通知。电子邮件 gem 是 Pony,并且有一个用于此通知的 haml 模板。

此逻辑适用于路线:

require 'sinatra'
require 'haml'
require 'pony'

get "/execute_all/?" do
  execute_all_tests()
  Pony.mail :to => "recipients@email.com",
      :from => "do-not-reply@email.com",
      :subject => "Test results,
      :html_body => haml(:email_layout)

      redirect "/"

end

但是,当我将计划作业与 rufus 调度程序一起用于这些操作时,出现以下异常:

scheduler caught exception:
undefined method `haml' for main:Object

代码是来自路线的copypasta:

   scheduler = Rufus::Scheduler.start_new
   scheduler.every '2h' do
      execute_all_tests()
      Pony.mail :to => "recipients@email.com",
          :from => "do-not-reply@email.com",
          :subject => "Test results,
          :html_body => haml(:email_layout)
   end

所有两种方法都在同一个文件中,执行该文件以运行 Sinatra 应用程序。

如何摆脱此异常,并按计划发送带有 haml 模板的电子邮件?

4

2 回答 2

7

The haml method is only available in the context of a request to Sinatra (it is an instance method on Sinatra::Base), and it can’t be used outside of a Sinatra request.

In order to render a Haml template, you can use the Haml API directly:

haml_template = File.read(File.join(settings.views, 'email_layout.haml'))

scheduler = Rufus::Scheduler.start_new
  scheduler.every '2h' do
    execute_all_tests()
    Pony.mail :to => "recipients@email.com",
      :from => "do-not-reply@email.com",
      :subject => "Test results",
      :html_body => Haml::Engine.new(haml_template).render(binding)
  end
end

Here I’m assuming execute_all_tests is using instance variables that are referenced in the Haml template, so we pass the binding to the Haml render method to access these variables. You might also need to pass in any Haml options you need as the second parameter to new.

于 2012-07-10T19:40:12.637 回答
1

您是否以同一用户身份运行 rufus 和 sinatra?这似乎是许多此类问题中反复出现的主题。

于 2012-07-09T05:33:22.877 回答