0

I want to sign_in my user inside my UserMailer using devise:

Desired behavior:

class UserMailer < ActionMailer::Base

  # need to include devise somehow

  def show_preview(user)
    sign_in(:user, user)
    response = RestClient.get 'http://localhost:3000/api/posts.json' #this needs authentication
    # email_body = format response ... ...
  end

end

Problem: I dont know which parts of devise I need to include in my UserMailer, and how to include them.

I've tried include Devise::Controllers::InternalHelpers (in order to use sign_in), from this link, but it seem to be deprecated.

Why: Because I want to have the same data in my email to the user, as what I show the user on the web app. So, I want to access the same api (ie localhost:3000/api/posts.json, which is what I use for my controlle/view, which requires that the user is authenticated.

Community
  • 1
  • 1
Sida Zhou
  • 3,529
  • 2
  • 33
  • 48

2 Answers2

2

You could make the request to the api before calling the mailer method and pass the data in as and argument.

You controller action could look something like this

def my_action
  response = RestClient.get 'http://localhost:3000/api/posts.json'
  UserMailer.show_preview(current_user, response)
  #render or redirect as needed
end

and you mailer could look something like this

class UserMailer < ActionMailer::Base

  # need to include devise somehow

  def show_preview(user, data)

    # email_body = format response ... ...
    @email_body = format data #this will make the data available to your view
  end

end
Aaron Dufall
  • 1,177
  • 10
  • 34
  • Upvoted for a good workaround in the situation i described. But in the real code base this solution is insufficient, as it will create too much of a mess. I still believe I really need to sign_in inside my mailer. – Sida Zhou Mar 23 '15 at 21:09
0

Currently I'm using a workaround which uses Rabl::Renderer:

class UserMailer < ActionMailer::Base
  class RablScope
    include ApplicationHelper # A way to include applicationHelper in Rabl::Engine
  end

  def show_preview(user)
    # @posts = function of user
    response = JSON.parse( Rabl::Renderer.new('api/posts/show',@posts,view_path: 'app/views', scope: RablScope.new()).render )
    # email_body = format response ... ...
  end
end

The downside is that I have to copy paste all the logic/code from the api controller into the mailer into # @posts = function of user otherwise this is sufficient.

Sida Zhou
  • 3,529
  • 2
  • 33
  • 48