Last active
          September 19, 2018 00:36 
        
      - 
      
- 
        Save wkrsz/5109643 to your computer and use it in GitHub Desktop. 
    Example on how to extract Devise user ID for Rails TaggedLogger.
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | config.log_tags = [ | |
| :remote_ip, | |
| ->(req){ | |
| if user_id = WardenTaggedLogger.extract_user_id_from_request(req) | |
| "#" + user_id.to_s | |
| else | |
| "guest" | |
| end | |
| } | |
| ] | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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 | 
This is a solution for: http://stackoverflow.com/questions/10811393/how-to-log-user-name-in-rails/13819155#13819155
;-) cool
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!
endComparison:
    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
  
            
This hack was sponsored by:
BrideZilla - Track Your Wedding Photography Clients & Be In Control