Skip to content

Instantly share code, notes, and snippets.

@wkrsz
Last active September 19, 2018 00:36
Show Gist options
  • Save wkrsz/5109643 to your computer and use it in GitHub Desktop.
Save wkrsz/5109643 to your computer and use it in GitHub Desktop.
Example on how to extract Devise user ID for Rails TaggedLogger.
config.log_tags = [
:remote_ip,
->(req){
if user_id = WardenTaggedLogger.extract_user_id_from_request(req)
"#" + user_id.to_s
else
"guest"
end
}
]
module WardenTaggedLogger
def self.extract_user_id_from_request(req)
session_key = Rails.application.config.session_options[:key]
session_data = req.cookie_jar.encrypted[session_key]
warden_data = session_data["warden.user.user.key"]
warden_data[0][0]
rescue
nil
end
end
@wkrsz
Copy link
Author

wkrsz commented Mar 7, 2013

This hack was sponsored by:
BrideZilla - Track Your Wedding Photography Clients & Be In Control

@wkrsz
Copy link
Author

wkrsz commented Mar 7, 2013

@christiaandegroot
Copy link

;-) cool

@fabn
Copy link

fabn commented Aug 7, 2015

Never use begin rescue in a critical path like this one:

require 'benchmark/ips'

good_hash = {
    'warden.user.admin_user.key' => [[1]]
}

bad_hash = {
}

Benchmark.ips do |x|
  x.report('begin+rescue good hash') { good_hash['warden.user.admin_user.key'][0][0] }
  x.report('has_key good hash') do
    good_hash.has_key?('warden.user.admin_user.key') &&
        good_hash['warden.user.admin_user.key'][0][0]
  end

  x.report('begin+rescue bad hash') { bad_hash['warden.user.admin_user.key'][0][0] rescue nil }
  x.report('has_key bad hash') do
    if bad_hash.has_key?('warden.user.admin_user.key')
      bad_hash['warden.user.admin_user.key'][0][0]
    end
  end

  # Compare the iterations per second of the various reports!
  x.compare!
end
Comparison:
    has_key bad hash:  4870164.1 i/s
begin+rescue good hash:  3544134.7 i/s - 1.37x slower
   has_key good hash:  2127500.6 i/s - 2.29x slower
begin+rescue bad hash:     4468.2 i/s - 1089.95x slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment