Why does single `=` work in `if` statement?

后端 未结 4 1193
囚心锁ツ
囚心锁ツ 2021-01-18 02:28

This code is provided as an example in for use with devise and OmniAuth, it works in my project.

class User < ActiveRecord::Base
  def self.new_with_sessi         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 03:13

    The only necessary thing for an if statement to be valid is a boolean expression. In this case, since = returns the result of the assignment, what's actually being tested is the falsiness of session["devise.facebook_data"].

    IntelliJ has a good point to lodge a complaint about code like this, as it's difficult to read without knowing a thing or two about Ruby. A recommendation would be to move that to an explicit assignment statement instead. This has the added benefit of DRYing up a reference to it twice.

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

提交回复
热议问题