Search code examples
ruby-on-railsrubyruby-on-rails-3monkeypatching

How to overload or monkeypatch Request.remote_ip or Request.ip?


I need to patch or overload Request.remote_ip (or would Request.ip be better as I see some mentioning that this should be used instead of remote_ip) such that it acts as normal, but if CF-Connecting-IP is in the header, it will return this IP address rather than the one it normally detects.

How do I set up this patch appropriately in terms of the class and method definition?

Essentially I'm trying to simply return the following for each request:

headers["CF-Connecting-IP"] || remote_ip

Solution

  • I wouldn't monkey patch a method on request. Instead, I'd make a helper method in your application controller that does exactly what you just posted:

    class ApplicationController < ActionController::Base
      ...
    
      def connecting_ip
        headers["CF-Connecting-IP"] || request.remote_ip
      end
    end
    

    And just use connecting_ip wherever this is important.