# Request.env variables in an observer

**URL:** <https://www.ruby-forum.com/t/request-env-variables-in-an-observer/158771>\
**Category:** Rails\
**Created:** [January 27, 2009, 8:39pm UTC](https://www.ruby-forum.com/t/request-env-variables-in-an-observer/158771 "2009-01-27T20:39:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dowker](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9f8e36/32.png) [@Dowker](https://www.ruby-forum.com/u/Dowker)\
**Post date:** [January 27, 2009, 8:39pm UTC](https://www.ruby-forum.com/t/request-env-variables-in-an-observer/158771/1 "2009-01-27T20:39:44Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Dowker](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/9f8e36/32.png) [@Dowker](https://www.ruby-forum.com/u/Dowker)\
**Post date:** [January 28, 2009, 4:09am UTC](https://www.ruby-forum.com/t/request-env-variables-in-an-observer/158771/2 "2009-01-28T04:09:49Z")

</div>

> 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.
