self.new_with_session(params,session)在这种情况下做了什么

时间:2017-06-08 21:53:00

标签: ruby-on-rails devise

我正在尝试在rails应用中实现facebook登录,并使用以下示例中的代码:https://github.com/rails-camp/facebook-omniauth-demo

# app/models/user.rb

def self.new_with_session(params, session)
  super.tap do |user|
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      user.email = data["email"] if user.email.blank?
    end
  end
end

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name   # assuming the user model has a name
    user.image = auth.info.image # assuming the user model has an image
  end
end

在这种情况下,self.new_with_session(params, session)方法具体做了什么?

1 个答案:

答案 0 :(得分:0)

你正在覆盖new_with_session功能。

def self.new_with_session(params, session)
  # call super(the overwritten function), it will return a resource and in this case you are
  # naming it 'user' in the block
  super.tap do |user|
    # if extra information was provided by facebook when user logged in, assign whatever comes in
    # session["devise.facebook_data"]["extra"]["raw_info"] to 'data' variable
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      # assign 'email' given by facebook in case the 'user' object doesn't have one yet
      user.email = data["email"] if user.email.blank?
    end
  end
end