I have a scenario were I would like to inject the IP address and UserAgent into an email when a database record is saved. I was thinking of implementing this via an observer but I don't know how to access the environment variables. Could anybody help or would this break Rails best practices and I should implement this differently. Thanks.
on 2009-01-27 20:39
on 2009-01-28 04:09
> I have a scenario were I would like to inject the IP address and > UserAgent into an email when a database record is saved. You need to trap the remote_ip and user_agent from the request method in the Controller instance for that request. That is where this information is received. Then you need to have this information available in the Active Record instance where the save is happening. One way to do this is to use the Thread class since both operations are ocurring on the same thread. There is a Thread.current object that you can stuff the info you need. In your application.rb controller file: class ApplicationController < ActionController::Base before_filter :log_ips private def log_ips Thread.current['remote_ip'] = request.remote_ip Thread.current['user_agent'] = request.user_agent end end Then somewhere your rails load path, either in lib or your models directory, add an active record extension. module ArExtension def self.included(m) m.class_eval do after_save :log_ips end end def log_ips puts Thread.current['user_agent'] # do you really want to email every request? you might want to do something else puts Thread.current['remote_ip'] end end ActiveRecord::Base.class_eval do include ArExtension end Hope that helps.