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