![](/img/trans.png)
[英]Facebook login with Ruby on Rails using omniauth-facebook gem
[英]Where does the method 'where' come from when using the Omniauth-Facebook gem?
將rubygems,Omniauth和Omniauth-Facebook集成到Rails應用程序中時,通常使用以下代碼。 我需要逐行對此代碼進行解釋。
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end
from_omniauth
是一個類方法,因此其內部任何沒有顯式接收器的方法(例如ab
具有顯式接收器a
)都使用隱式接收器( self
)-對於類方法, self
指代類本身。 因此, where
User類上調用的位置由ActiveRecord Query接口定義。 因此where()
可以像User.where()
一樣容易地編寫,但是遺漏不需要的顯式接收器是很習慣的(因為它使重構類名更加容易,等等)。
where
的參數是語句auth.slice(:provder, :uid)
。 在這里, auth
基本上是一個哈希。 (它實際上是一個HASHIE對象,它是具有附加功能的哈希值。)所以auth.slice
最終調用哈希#片 -這將只返回一個只包含被傳遞到鍵/值的新的Hash slice
,留給你{ provider: "facebook", uid: "THE_UID_HERE" }
。 因此,總體結果是執行User.where(provider: "facebook", uid: "THE_UID_HERE")
。
然后,調用first_or_initialize
來查找與這些屬性匹配的User對象,或者初始化一個新的對象(不保存它)。
最后,在生成的對象上調用tap
並將其設置為等於該對象的塊范圍方法user
,並在塊的末尾返回user。 基本上,這是代替創建局部變量user
。 因此,有效地,它在找到或初始化的User對象上的塊中設置所有屬性,然后save!
用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.