ruby 如何在ActionMailer中为各个用户设置* url_options *

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 如何在ActionMailer中为各个用户设置* url_options *相关的知识,希望对你有一定的参考价值。

class User < ActiveRecord::Base
  # Returns the users url options.
  #
  # * +host+ - required
  # * +port+ - optional. defaults to +nil+
  # * +scheme+ - optional. defaults to 'http'
  def url_options
    {
      host: 'www.example.com'
    }
  end
end
class MyMailer < ActionMailer::Base
  def welcome(user)
    @url_options = user.url_options
    mail to: user.email
  end

  # Returns default url options for the mailer instance.
  # This is used in <tt>link_to</tt>, <tt>url_for</tt> and named route helpers
  # to build full urls. When you use named route helper make sure to always use
  # the <tt>named_route_url</tt> style to create absolute urls!
  # Remember to add <tt>only_path: false</tt> when you use <tt>url_for</tt> to
  # create absolute urls!
  #
  # This uses the instance variable <tt>@url_options</tt> that you can use to
  # provide url options for example for the user that you send the mail to.
  #
  #   def welcome(user)
  #     @url_options = user.url_options
  #     mail to: asset.user.email
  #   end
  #
  # Example
  #
  #   {
  #     host: 'www.example.com'
  #   }
  #
  # All possible options:
  #
  #   {
  #     host: 'www.example.com',
  #     port: 3000
  #     scheme: 'http'
  #   }
  #
  def url_options
    super.merge(@url_options || {})
  end

  # Returns a full url for a custom path.
  # Uses <tt>url_options</tt> to build the full url if it isn't already a full url.
  #
  # custom_url '/script.asp?foo=bar'
  # => "http://www.example.com/script.asp?foo=bar"
  #
  def custom_url(url)
    uri = URI.parse(url)
    url_options.each do |k,v|
      uri.send("#{k}=", v) if uri.respond_to?(k) && uri.send(k).nil?
    end
    uri.scheme ||= 'http'
    uri.to_s
  end
  helper_method :custom_url
end

以上是关于ruby 如何在ActionMailer中为各个用户设置* url_options *的主要内容,如果未能解决你的问题,请参考以下文章

Rails 4, RSpec 3.2 - 如何模拟 ActionMailer 的 Deliver_now 方法来引发异常

如何在 Ruby 中为 splat 参数设置默认值

如何在 Ruby 脚本中为命令 shell 获取环境变量?

使用 ActionMailer 和 Outlook/Mandrillapp SMTP 服务器发送邮件

如何在 Ruby 中为 IRCbot 实现登录/管理系统?

如何在Ruby中为每个id创建哈希