module SessionLogger module SessionLogging extend ActiveSupport::Concern module ClassMethods #:nodoc: # Options are the same as the ones for around filter. See docs for around filter def enable_session_logging(options={}) raise "Session Logging can't occur without specifying logged_models in initializers" if SessionLogger.logged_models.blank? SessionLogger::SessionObserver.observe(SessionLogger.logged_models) if !ActiveRecord::Base.observers.include? SessionLogger::SessionObserver ActiveRecord::Base.observers << SessionLogger::SessionObserver if defined?(ActiveRecord) and defined?(ActiveRecord::Base) end sweeper_instance = SessionLogger::SessionObserver.instance around_filter(sweeper_instance, options) end end end class SessionObserver < ActiveRecord::Observer attr_accessor :controller #Required to prevent the observer from un-cleverly looking for Session... def self.observed_class nil end # ------------------------------------------- Legacy around filter calls def before(controller) self.controller = controller true # before method from SessionObserver should always return true end def after(controller) self.controller = controller # Clean up, so that the controller can be collected after this request self.controller = nil end # ------------------------------------------- ActiveRecord callbacks def before_create(record) return if controller.blank? || controller.session.blank? candidate_columns = record.attributes.select { |attr| attr.starts_with? SessionLogger.model_prefix } candidate_columns.keys.each do |column| column = column.to_s #Only setting if present prevents empty strings from overriding defaults in the schema set_if_present(record, column, controller.session[column]) end #pp controller.session["sl_campaign"] #pp record end private def set_if_present(obj, key, val) pp obj pp key pp val obj.send("#{key}=", val) if val.present? end end end