How can I use Devise's `confirmation_url` outside of a mailer?

devise, ruby, ruby-on-rails

Solution

Ok so after fighting with this for a while I decided to read the explanation near the top of this file:

https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/url_helpers.rb

It turns out that what Devise generates by default (at least on my app) are routes. `confirmation_url` is a helper, but you can still see the routes Devise generates:

rake routes | grep confirm

Since I am using a model called `Account` instead of `User`, that gives me this:

account_confirmation     POST /accounts/confirmation(.:format)  accounts/confirmations#create
new_account_confirmation GET  /accounts/confirmation/new(.:format) accounts/confirmations#new
                         GET  /accounts/confirmation(.:format)                         accounts/confirmations#show
confirm_account        PATCH  /accounts/confirmation(.:format)                         accounts/confirmations#update

By looking at the generated emails I confirmed that the emails looked like this:

http://myserver.com/accounts/confirm?confirmation_token=xxxx

This is the third route on the listing above - the second GET. For reasons unknown to me, rails does not print the name of show-like routes, but you can deduce it from the POST at the top; the route is named `account_confirmation`. So now I can use the rails url helper to generate the url myself:

Rails.application
     .routes.url_helpers
     .account_confirmation_url(confirmation_token: account.confirmation_token)

Which will return an url like the one above. Remember to replace `account` by `user`, or whatever else you are authenticating with Devise.

Problem

I am using Devise in a rails project. I want to pass the confirmation url to a third party. That url is produced by the expression `confirmation_url(@resource, confirmation_token: @token)` in the following Devise Mailer view: https://github.com/plataformatec/devise/blob/master/app/views/devise/mailer/confirmation_instructions.html.erb I have grepped the whole source code of Devise trying to figure out who or where is `confirmation_url` defined, but I could not find anything; it only appears on the views, so it must be dynamically generated by something. In a regular Rails app, I can use `Rails.application.routes.url_helpers` to produce urls (ex. `Rails.application.routes.url_helpers.user_path(@user)`). Is there anything similar I can use to invoke `confirmation_url` outside of the mailer views?

Original source

Related problems