Rails ActionMailer lib目录

时间:2015-09-21 22:50:27

标签: ruby-on-rails ruby actionmailer

我正在尝试从lib目录中的文件发送邮件。我使用Action Mailer Basics来帮助我配置它。我可以成功地从我的控制器发送邮件,所以我认为我的问题不正确地要求我的lib文件中的邮件“filename.rb”。

我运行ruby filename.rb并获得

/pathtofile/lib/otherfile.rb:37:in `alert': uninitialized constant UserMailer (NameError)
from filename.rb:47:in `block in <main>'
from filename.rb:35:in `secondly_loop'
from filename.rb:47:in `<main>'

filename.rb

alert

otherfile.rb

def alert
  #send email http://www.gotealeaf.com/blog/handling-emails-in-rails
  UserMailer.mailer_method().deliver_now
  puts "Sent Email"
end #end def alert

应用/邮寄者/ user_mailer.rb

class UserMailer < ApplicationMailer
  default from: 'email@email.com'

  def mailer_method(a)
    @a = a
    mail(to: 'email@email.com', subject: "Hello you have new mail")
  end
end

应用/视图/ mailer_method.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h2>Daniel, </h2>
    <p>Your email is boring and has arrived now.<br><br>
      Sincerely,<br>
      Daniel</p>
  </body>
</html>

3 个答案:

答案 0 :(得分:0)

Rails为您自动加载模型。只是致电ruby filename.rb,不会为您加载UserMailer,因此您会收到uninitialized constant错误,因为当前名称空间中没有定义UserMailer

编辑这是一个允许您致电alert的SSCCE:请注意它位于MyAlert的名称空间内; Rails自动加载UserMailer,以便可以在MyAlert的命名空间内访问它。

为了简洁和明确,我稍微改变了一些定义。

<强> my_alerts.rb

class MyAlerts
  def self.alert
    UserMailer.mailer_method("It worked")
    puts "Sent Email"
  end 
end

<强> application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  default from: "from@example.com"
  layout 'mailer'
end

<强> user_mailer.rb

class UserMailer < ApplicationMailer
  default from: 'email@email.com'

  def self.mailer_method(a)
    puts a
  end
end

<强>输出:

lbrito@lbrito:~/Documents/rails/textgen$ rails c
Loading development environment (Rails 4.2.4)
2.2.1 :001 > MyAlerts.alert
It worked
Sent Email
 => nil 

答案 1 :(得分:0)

这是使用require的更新示例。注意我不建议实际执行此操作,因为这应该设置为rake任务,所以这纯粹是使用require的示例:

<强> LIB / filename.rb

parse deploy

<强> LIB / my_alert.rb

#!/usr/bin/env ruby

require_relative './my_alert'

MyAlert.alert

应用/邮寄者/ user_mailer.rb

require_relative '../app/mailers/user_mailer'

class MyAlert
  def self.alert
    #send email
    UserMailer.mailer_method("foo").deliver_now
    puts "Sent Email"
  end
end

我已经让它在测试应用程序中工作,以便它可以访问UserMailer,但由于这实际上不是作为rails应用程序运行,您需要添加更多代码以让ActionMailer知道在哪里查找模板。制作rake任务实际上将通过Rails运行它,这将是首选。

答案 2 :(得分:0)

如果您正在使用rails lib文件夹,那么您应该使用rails来运行您的代码。您正在尝试运行包含rails上下文之外的rails组件的ruby代码。当您运行ruby filename.rb时,您将通过所有进入rails自动加载的魔法。 ActionMailer是一个gem,通常在运行rails服务器时通过bundler为你加载gem。看看你的config/applicarion.rb,了解我正在采取的措施。如果您仍然感到困惑,请阅读:http://guides.rubyonrails.org/autoloading_and_reloading_constants.html

我认为你想要做的是构建一个rails引擎。这样,您可以保持代码模块化,但仍然可以访问所有各种rails组件和宝石,例如ActionMailer。有一百万个关于如何构建rails引擎的惊人教程可以帮助你入门,但我会先阅读ruby on rails官方指南。