Rails: Accessing Controller Variables in a Sweeper

403 views Asked by At

So I have some code here I need to modify regarding a Rails Sweeper:

class UserTrackingSweeper < ActionController::Caching::Sweeper
  observe User

  def after_update(user)
    return if user.nil? || user.created_at.nil? #fix weird bug complaining about to_date on nil class
    return if user.created_at.to_date < Date.today || user.email.blank?

    user.send_welcome_email if user.email_was.blank?
  end

  #use sweeper as a way to ingest metadata from the user access to the site automatically
  def after_create(user)
    begin
      if !cookies[:user_tracking_meta].nil?
        full_traffic_source = cookies[:user_tracking_meta]
      else
        if !session.empty? && !session[:session_id].blank?
          user_tracking_meta = Rails.cache.read("user_meta_data#{session[:session_id]}")
          full_traffic_source = CGI::unescape(user_tracking_meta[:traffic_source])
        end
      end
      traffic_source = URI::parse(full_traffic_source).host || "direct"
    rescue Exception => e
      Rails.logger.info "ERROR tracking ref link. #{e.message}"
      traffic_source = "unknown"
      full_traffic_source = "unknown"
    end

    # if I am registered from already, than use that for now (false or null use site)
    registered_from = user.registered_from || "site" 
    if params && params[:controller]
      registered_from = "quiz" if params[:controller].match(/quiz/i)
      # registered_from = "api" if params[:controller].match(/api/i)
    end


    meta = {
      :traffic_source => user.traffic_source || traffic_source,
      :full_traffic_source => full_traffic_source,
      :registered_from => registered_from,
      :id_hash => user.get_id_hash
    }
    user.update_attributes(meta)
  end

end

The problem is I've noticed that it dosen't seem possible to access the cookies and parameters hash within a sweeper yet it appears fine in some of our company's integration environments. It does not work in my local machine though. So my questions are:

  1. How is it possible to access params / cookies within a Sweeper?
  2. If it's not possible, what would you do instead?

Thanks

1

There are 1 answers

0
Fabio Russo On

I'm sure you can use session variables in a Cache Sweeper so if anything put whatever you need there and you're set