Highlight changes being made on ActiveRecord object inside email

I simply needed one helper method which would help me highlight changes being made on any ActiveRecord object inside email. Below is one example of that I have come up with and would like to extend it in my future projects too.

It gave me some insights into ActiveRecord::Base#previous_changes and ActiveRecord::Base#reflections. Nice to learn such ActiveRecord features.

samg/diffy also helped me out decorating text changes

Screenshot from 2014-01-16 13:50:15

Adding to my MailerHelper


module MailerHelper
def highligh_changes_made_to object, options={}
html = ""
attrs = options[:attrs] || object.class.attribute_names
html << "<br/><p>"
attrs.each do |attr|
html << "<p> #{attr.to_s.humanize} : "
if object.previous_changes.include? attr.to_s
if object.class.columns_hash[attr.to_s].type==:text
html << "<br/>"
html << text_changes(object.previous_changes[attr.to_s][0], object.previous_changes[attr.to_s][1])
else
html << "<font color='gray'>#{object_attr object, attr, object.previous_changes[attr.to_s][0]}</font> => "
html << "<b>#{object_attr object, attr, object.previous_changes[attr.to_s][1]}</b>"
end
else
html << "#{object_attr object, attr, (object.send attr.to_sym)}"
end
html << "</p>"
end
html << "<p/><br/>"
html.html_safe
end
def object_attr object, attr, foreign_key_value
return foreign_key_value unless attr.ends_with? "_id"
assoc = object.class.reflections.values.select{ |assoc| assoc.foreign_key==attr }.first
return "<NotFound>" unless assoc
assoc.klass.where(:id => foreign_key_value).first || '""'
end
def text_changes str1, str2
Diffy::Diff.new( str1, str2).collect do |line|
case line
when /^\+/ then
"<b>#{line[1..-1]}</b>"
when /^-/ then
"<font color='gray'>#{line[1..-1]}</font>"
when /^\// then
else
line
end
end.join("<br/>").to_s
end
end
class ActionMailer::Base
helper MailerHelper
end

My rails mailer knows request and current_user

How about accessing @request and @current_user in your mailer


# config/initializers/mailer_knows.rb
module MailerBefore
def before(hash)
hash.keys.each do |key|
define_method key.to_sym do
eval " @#{key} = hash[key] "
end
end
end
end
class ActionMailer::Base
extend MailerBefore
end
class ActionController::Base
before_filter :mailer_knows
def mailer_knows
ActionMailer::Base.before({
:request => request,
:current_user => (current_user and current_user.dup)
})
end
end

view raw

mailer_knows.rb

hosted with ❤ by GitHub