Execute JS code on user sign up/sign in with Rails

2019-05-11 12:59发布

问题:

I'm looking at the Kissmetrics (analytics app) JS API docs, and they have an "identify" method that lets you tell Kissmetrics about a user. Here's what their docs say:

We recommend you call identify in two scenarios:

When a user successfully signs up When a user successfully logs in, either through cookies or through a login page

What would be the best way to achieve that? How can I detect when a user has just signed up or signed in?

回答1:

Lets divide the problem in two: register and log in.

You can detect when a new user has registered in you app just adding a after_create hook in you User model. Something like

class User < ActiveRecord::Base
  after_create :register_hook

  def register_hook
    # your code here
  end
end

Detecting when the user logs in is a little bit dirtier. Devise modify the user.current_sign_in_at attribute of the user when he/she logs in, so you could add a before_save hook in the user model and check if the current_sign_in_at attribute has changed. It should be something like:

class User < ActiveRecord::Base
  before_save :login_hook, :if => current_sign_in_at_changed?

  def login_hook
    # your code here
  end
end

Once you have the right callbacks for detecting sign in/sign up, you can just create a cookie with the info and read it from the javascript or write a helper method for the User model and write something like this in your layout:

<% if current_user.just_signed_in %>
  <script type="text/javascript">
    // Your sign in stats code here
  </script>
<% end %>

<% if current_user.just_signed_up %>
  <script type="text/javascript">
    // Your sign up stats code here
  </script>
<% end %>

Following this way, the complete model would be:

class User < ActiveRecord::Base
  after_create :register_hook
  before_save :login_hook, :if => current_sign_in_at_changed?

  attr_accessor :just_singed_up, :just_signed_in

  def register_hook
    @just_signed_up = true
  end

  def login_hook
    @just_signed_in = true
  end
end