Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does self.new_with_session(params, session) do in this case

I am trying to implement facebook login in a rails app and I used the code from the following example: 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

What does the method self.new_with_session(params, session) do specifically in this case?

like image 625
ab-CS Avatar asked Dec 12 '25 03:12

ab-CS


1 Answers

you're overwriting new_with_session function.

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
like image 178
fanta Avatar answered Dec 14 '25 02:12

fanta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!