Forum: Ruby on Rails request.env variables in an observer

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E4e9e36d6730fd5a99e56ec4f53172ff?d=identicon&s=25 Dowker (Guest)
on 2009-01-27 20:39
(Received via mailing list)
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.
47c3af2d56d44eb1d08a601c837a1262?d=identicon&s=25 alberto (Guest)
on 2009-01-28 04:09
(Received via mailing list)
> 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.
This topic is locked and can not be replied to.