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

佐手、 提交于 2019-12-05 22:58:46

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!