Dynamic domain name in Rails action mailer while using sidekiq - ruby-on-rails

In my requirement ,there are different domain names for single project.I would like to send reset password link with a domain name where the user requested for the reset password.For that I have done the follows in application_controller.rb and it works well.
before_filter :set_mailer_host
def set_mailer_host
ActionMailer::Base.default_url_options[:host] = request.host_with_port
$url_host = request.host_with_port
end
Later,I have used sidekiq for delayed mailer and updated like follows on entire application
Notifier.delay.password_reset(user.id)
As the mailer was configured with sidekiq it was using default domain name provided in configuration only and it was not using the dynamic domain name provided from request on application_controller.rb
Any suggestion to get the dynamic domain on mailers running by sidekiq would be greatly appreciated.
Rails - 3.2.8
Ruby - 1.9.3
sidekiq - 2.13.1
Thanks!!!

One of the options would be to associate each user with a domain and use this information when sending the email in sidekiq.

You'll need to construct the url yourself rather than rely on AM to do it for you.

Related

Passing multiple arguments to Rack middleware in Rails application.rb

I am creating a Rack Middleware which I want to use in my Rails App. Basically, I need to log requests matching particular urls to my Database. In order to do this I need to pass database configuration to my Middleware so it can establish connection with DB. I am trying to do:-
db_yml = Rails.root.join('config/database.yml')
db_config = YAML.load(db_yml.read)[Rails.env]
But this is giving an error
config/application.rb:40:in <class:Application>': undefined methodread' for # (NoMethodError)
If I add byebug and run the same in the byebug console it works fine. I am not able to find out why. I want to do following things:-
I need to read & modify the database configuration before passing it to my middleware as argument.
I want to read the domain of the request url. We are using Apartment gem and Our schema name will be the domain name.
I followed multiple articles here & here.
I am a newbie to Rails and don't know good resources so please help.
Thanks in advance!
You should use:
db_yml = Rails.root.join('config/database.yml')
db_config = YAML.load(File.open(db_yml))[Rails.env]
Rails.root.join('config/database.yml') return the file path which is a string.

Rails 3 sessions not lazy loading

I've read that sessions in Rails 3 are lazy loaded, but I'm not seeing that behavior. To test this, I created a new Rails 3.2 app using MySQL and the activerecord session store. No gems added except the V8 JavaScript engine. Then I created an empty controller called welcome with an index action. No code in here at all. When I hit the index page, I see a session created in the sessions table in MySQL.
Am I doing something wrong? I thought a session would only be created if I accessed it.
That's a default behavior of Ruby on Rails beginning from version 3.0 I guess. See:
http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf
If you need to stop sessions being created in the database for bots/crawlers, this is what worked for me:
# Save this file as config/initializers/session_store_ext.rb
# and don't forget to define BOT_REGEX to match bots/crawlers
class ActiveRecord::SessionStore
_set_session = instance_method :set_session
define_method :set_session do | env, sid, session_data, options |
unless env['HTTP_USER_AGENT'] =~ BOT_REGEX
_set_session.bind(self).call env, sid, session_data, options
end
sid
end
private :set_session
end
I've written a blog post explaining how I created this and why it works - Conditionally Disabling Database Sessions in Ruby on Rails 3

Devise and mailers - How to get current URL

When sending emails (for example for 'Reset password instructions') using Devise, i need to know current domain URL, and set that value into mailer's template.
request.url doesn't work for me.
Assuming, this Rails application is accessibly from multiple URLs.
Any ideas?
Request object is not available in the mailers. You will need to set up the host in the environment configuration file with something like:
ActionMailer::Base.default_url_options[:host] = 'myhost.com'

How do I preview emails in Rails?

This might be a dumb question but when I'm putting together an HTML email in Rails, is there a particularly easy built-in way to preview the template it in the browser or do I need to write some sort of custom controller that pulls it in as its view?
Action Mailer now has a built in way of previewing emails in Rails 4.1. For example, check this out:
# located in test/mailers/previews/notifier_mailer_preview.rb
class NotifierPreview < ActionMailer::Preview
# Accessible from http://localhost:3000/rails/mailers/notifier/welcome
def welcome
Notifier.welcome(User.first)
end
end
Daniel's answer is a good start, but if your email templates contain any dynamic data, it won't work. E.g. suppose your email is an order receipt and within it you print out #order.total_price - using the previous method the #order variable will be nil.
Here's a little recipe I use:
First, since this email preview functionality is definitely for internal use only, I set up some generic routes in the admin namespace:
#routes.rb
MySite::Application.routes.draw do
namespace :admin do
match 'mailer(/:action(/:id(.:format)))' => 'mailer#:action'
end
end
Next, I create the controller. In this controller, I create one method per email template. Since most emails contain dynamic data, we need to populate whatever member variables the template expects.
This could be done with fixtures, but I typically prefer to just grab some pseudo-random real data. Remember - this is NOT a unit test - this is purely a development aid. It doesn't need to produce the same result every single time - in fact - it's probably better if it doesn't!
#app/controllers/admin/mailer_controller.rb
class Admin::MailerController < Admin::ApplicationController
def preview_welcome()
#user = User.last
render :file => 'mailer/welcome.html.erb', :layout => 'mailer'
end
end
Note that when we render the template, we use layout=>:mailer. This embeds the body of your email inside the HTML email layout that you've created instead of inside your typical web application layout (e.g. application.html.erb).
And that's pretty much it. Now I can visit http://example.com/admin/mailer/preview_welcome to preview change to my welcome email template.
37Signals also has their own mail testing gem called mail_view. It's pretty fantastic.
The easiest setup I've seen is MailCatcher. Setup took 2 minutes, and it works for new mailers out of the box.
I use email_preview. Give it a try.
Easiest solution in rails 6: just remember one url:
http://localhost:3000/rails/mailers
I'm surprised no one's mentioned letter_opener. It's a gem that will render and open emails as a browser page whenever an email is delivered in dev.
I recently wrote a gem named Maily to preview, edit (template file) and deliver the application emails via a browser. It also provides a friendly way to hook data, a flexible authorization system and a minimalist UI.
I have planned to add new features in the near future, like:
Multiple hooks per email
Parametrize emails via UI (arguments of mailer method)
Play with translations keys (list, highlight, ...)
I hope it can help you.
rails generates a mail preview if you use rails g mailer CustomMailer.
You will get a file CustomMailerPreview inside spec/mailers/previews folder.
Here you can write your method that will call the mailer and it'll generate a preview.
For ex -
class CustomMailerPreview < ActionMailer::Preview
def contact_us_mail_preview
CustomMailer.my_mail(user: User.first)
end
end
Preview all emails at http://localhost:3000/rails/mailers/custom_mailer
You can use Rails Email Preview
REP is a rails engine to preview and test send emails, with I18n support, easy premailer integration, and optional CMS editing with comfortable_mexican_sofa.
There is no way to preview it directly out of the Mailer.
But as you wrote, you can write a controller, which looks something like this.
class EmailPreviewsControllers < ActionController::Base
def show
render "#{params[:mailer]}_mailer/#{params[:method]}"
end
end
But I think, that's not the best way to test emails, if they look correctly.
Rails Email Preview helps us to quickly view the email in web browser in development mode.
1) Add “gem ‘rails_email_preview’, ‘~> 0.2.29’ “ to gem file and bundle install.
2) Run “rails g rails_email_preview:install” this creates initializer in config folder and add routes.
3) Run “rails g rails_email_preview:update_previews” this crates mailer_previews folder in app directory.
Generator will add a stub to each of your emails, then u populate the stub with mock data.
Ex:
class UserMailerPreview
def invitation
UserMailer.invitation mock_user(‘Alice’), mock_user(‘Bob’)
end
def welcome
UserMailer.welcome mock_user
end
private
def mock_user(name = ‘Bill Gates’)
fake_id User.new(name: name, email: “user#{rand 100}#test.com”)
end
def fake_id(obj)
obj.define_singleton_method(:id) { 123 + rand(100) }
obj
end
end
4) Parameters in search query will be available as an instance variable to preview class. Ex: if we have a URL like
“/emails/user_mailer_preview-welcome?user_id=1” #user_id is defined in welcome method of UserMailerPreview it helps us to send mail to specific user.
class UserMailerPreview
def welcome
user = #user_id ? User.find(#user_id) : mock_user
UserMailer.welcome(user)
end
end
5) To access REP url’s like this
rails_email_preview.rep_root_url
rails_email_preview.rep_emails_url
rails_email_preview.rep_email_url(‘user_mailer-welcome’)
6) We can send emails via REP, this will use environment mailer settings. Uncomment this line in the initializer to disable sending mail in test environment.
config.enable_send_email = false
Source : RailsCarma Blog : Previewing Emails in Rails Applications With the Mail_View Gem
I prefer mails_viewer gem. This gem is quite useful as it save the HTML template into tmp folder.

Rails - How to obtain an absolute URL for the site? https://example.com

For one of my models I have a method:
def download_url
url = xxxxx
end
which works nicely to make /xxxx/xxxx/3
What i want to do is updated this to include an absolute URL so I can use this method in an email:
https://example.com/xxxx/xxxx/3
But I don't want to hard code. I want it to be an environment var so it works on dev & production
Emails are effectively views, and can use helpers. The model shouldn't really have any knowledge about the views - instead, you should use url_for or one of its descendant methods in the email view template to generate a URL. Those helpers can generate absolute URLs based on the location that the application is running (and associated configuration - you'll want to set config.action_mailer.default_url_options[:host] in your environment file) without having to mess with environment variables and the like.
I would define the domain as a constant in development.rb & production.rb:
APP_DOMAIN = "https://mysite.com"
And then just use this constant in your method within the model:
def download_url
"#{APP_DOMAIN}/download/#{id}"
end
It may be ugly, but it's necessary. Rails apps don't and shouldn't know their root URL. That's a job for the web server. But, hardcoding sucks...
If you're using capistrano or some other deployment method, you can define the server host in a variable and write it out to a file that you can read from the app.

Resources