【问题标题】:Undefined method `haml' when rendering haml in Pony mail from scheduled job从预定作业中渲染 Pony 邮件中的 haml 时未定义的方法“haml”
【发布时间】:2012-07-08 09:42:31
【问题描述】:

我有一个 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模板的电子邮件作为预定作业发送?

【问题讨论】:

    标签: sinatra haml rufus-scheduler pony


    【解决方案1】:

    haml 方法仅在向 Sinatra 请求的上下文中可用(它是 Sinatra::Base 上的实例方法),不能在 Sinatra 请求之外使用。

    为了渲染一个Haml模板,你可以直接使用Haml API:

    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
    

    这里我假设 execute_all_tests 正在使用在 Haml 模板中引用的实例变量,因此我们将 binding 传递给 Haml render 方法来访问这些变量。您可能还需要将所需的任何 Haml 选项作为第二个参数传递给 new

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多