Skip to content

Instantly share code, notes, and snippets.

@Chocksy
Forked from Lukom/email_previews.rb
Last active April 2, 2021 18:45
Show Gist options
  • Save Chocksy/2e3c55fd713a3b5f5975ba188418666c to your computer and use it in GitHub Desktop.
Save Chocksy/2e3c55fd713a3b5f5975ba188418666c to your computer and use it in GitHub Desktop.
Preview Emails in ActiveAdmin / Rails 5.1
-# app/admin/email_previews.rb
# frozen_string_literal: true
ActiveAdmin.register_page 'Email Previews' do
menu parent: 'dashboard', priority: 10
content do
div 'Select a mailer from the sidebar.'
end
sidebar 'Mail Previews' do
Dir['spec/mailer_previews/**/*_preview.rb'].each do |preview_path|
preview_mailer = File.basename(preview_path, '.rb')
mailer = preview_mailer.chomp('_preview')
div { strong { mailer } }
preview_mailer_class = preview_mailer.camelize.constantize
mails = preview_mailer_class.public_instance_methods(false).map(&:to_s).sort
mails.each do |mail|
div { link_to mail, {action: :preview, mailer: mailer, mail: mail} }
end
br
end
end
page_action :preview
end
-# app/views/admin/email_previews/preview.html.slim
iframe src="/admin/mailers/#{params[:mailer]}/#{params[:mail]}" style="width: 100%; height: 1000px; border: 2px solid lightgrey;"
# config/initializers/preview_emails.rb
# frozen_string_literal: true
Rails.application.configure do
config.action_mailer.show_previews = true
config.action_mailer.preview_path ||= Rails.root.join('spec/mailer_previews')
config.autoload_paths += [config.action_mailer.preview_path]
routes.append do
get '/admin/mailers' => 'rails/mailers#index'
get '/admin/mailers/*path' => 'rails/mailers#preview'
end
end
class Rails::MailersController
before_action :require_admin
private
def require_admin
redirect_to root_path unless current_user&.admin?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment