6ft Dan
6ft Dan

Reputation: 2435

Rails grab template file as string variable in controller

I'm creating a custom ActionMailer which will also send Direct Messages on Twitter, and Text Message through Twilio. I need each to receive a parameter of the body of the message. I need to use the current template as a string variable.

For example:

# calling send_invite's mail method will load the send_invite template
def send_invite(to)
  mail(to: to) # body parameter is automatically rendered from template
end

Now if I modify it to send through other services:

def send_invite(to, option)
  if option == :email
    mail(to: to) # body parameter is automatically rendered from template
  elsif option == :twitter
    twitter.create_direct_message(to, NEED_TEMPLATE_AS_STRING_HERE)
  elsif option == :sms
    twilio.sms(to, NEED_TEMPLATE_AS_STRING_HERE)
  end
end

How might I grab the template for each of these service calls? Would there be something like:

message(to, render layout: false)
# or
message(to, IO.read template_path_helper("template") )
# or
message(to, template_helper.to_s)

How might I get the template as a string for my message body in these other methods? What's the Rails Way to do it? The templates are erb files and need to be able to render the appropriate variable as they would from a render.

I need to do it this way for translations of templates to be available.

Upvotes: 0

Views: 746

Answers (1)

Marcelo Ribeiro
Marcelo Ribeiro

Reputation: 1738

I think you can create the template string from the controller, and send it to your mailer, like this:

@parsed_template = render_to_string(:partial => 'my_partial', :layout => false, :locals => {:my_object => my_value})

SomeMailer.send_invite(to, option, @parsed_template).deliver

Upvotes: 1

Related Questions