LoginSignup
10
13

More than 5 years have passed since last update.

config.action_mailer.default_url_options に対する正しい localhost の定義

Last updated at Posted at 2015-02-17

恥ずかしながら今知った、というお話です。

メール送信を行うWebアプリの場合、config.action_mailer.default_url_options の定義が必要になると思いますが、開発環境向けには以下のような定義の仕方が良く紹介されています。

/config/environments/development.rb
config.action_mailer.default_url_options = { host: "localhost:5000" }

うちは foreman なんでポート番号が5000番ですが、一般的には3000番でしょうか。

しかし正しい定義の仕方はこちらなんですね。

/config/environments/development.rb
config.action_mailer.default_url_options = { host: "localhost", port: "5000" }

ポート番号の方は数値なのでクオートしなくても大丈夫かな?要するに本来は host と port を別々に定義する必要がある、というお話です。

気づいたのは、メール送信時にこんな例外が出たことから。

URI::InvalidComponentError - bad component(expected host component): localhost:5000:
  /Users/oakbow/.rbenv/versions/.../uri/generic.rb:605:in `check_host'
  /Users/oakbow/.rbenv/versions/.../uri/generic.rb:646:in `host='
  /Users/oakbow/.rbenv/versions/.../uri/generic.rb:195:in `initialize'
  /Users/oakbow/.rbenv/versions/.../uri/generic.rb:141:in `build'
  roadie (2.4.3) lib/roadie/inliner.rb:211:in `absolute_url_base'
  roadie (2.4.3) lib/roadie/inliner.rb:192:in `ensure_absolute_url'
  roadie (2.4.3) lib/roadie/inliner.rb:180:in `block in make_image_urls_absolute'
     :

調べてみると、メールテンプレートの link_to で絶対URIを解決する時に出てたんですね。
どうやら HTMLメール用の gem である roadie が、ホスト名の中にポート番号が入っている場合を考慮してパースしてくれないのが直接的な原因だったようです。
上のスタックトレースから追って Roadie::Inliner#absolute_url_basehost みたら localhost:5000 がそのまんま入っていて、 port が空だったので、たぶん。
誰にでも起きる問題ではないと思いますが、ハマる時にはハマると思いますので、FYI として。

10
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
13