2012-09-17 98 views
0

我遇到了麻煩下面的方法在我的用戶模型來處理哈希(「權威性」)我是從LinkedIn獲取用戶登入檢索數據稍後在我的用戶模型中調用'deep_get'方法,因爲我使用omniauth/linkedin gem創建了一個用戶。然而,它的返回了,我知道是不是零提供商/ UID /標題/電子郵件用戶字段零值。注射方法從哈希

我包括FIRST_NAME和姓氏領域作爲例子,因爲這種方法的工作(不返回零值),但(我知道)不良作風/異常處理。任何想法,爲什麼我的deep_get注入方法不工作來檢索散列中的數據,因爲我喜歡它?

def self.create_from_omniauth(auth) 

     create! do |user| 

     # i'd like to retrieve user information from linkedin per the following with my inject method, but i am getting nil values when i should be getting data. 

     # :provider and :uid are on the same branch level of data. first_name,last_name,email,etc. are on a branch just below called 'info' 

     user.provider = deep_get(auth, :provider) 
     user.uid = deep_get(auth, :uid) 
     user.headline = deep_get(auth, :info, :headline) 
     user.email = deep_get(auth, :info, :email) 

     # the below is working but i know pokemon exception handling is not good style. 

     begin 
      user.first_name = auth["info"]["first_name"] 
     rescue 
     end 

     begin 
      user.last_name = auth["info"]["last_name"] 
     rescue 
     end 

回答

0

試試這個

def deep_find(obj,key) 
    if obj.respond_to?(:key?) && obj.key?(key) 
    obj[key] 
    elsif obj.respond_to?(:each) 
    r = nil 
    obj.find{ |*a| r=deep_find(a.last,key) } 
    r 
    end 
end 
or try this 
class Hash 
    def deep_fetch(key, default = nil) 
    default = yield if block_given? 
    (deep_find(key) or default) or nil 
    end 

    def deep_find(key) 
    if key?(key) 
     self[key] 
    else 
     self.values.inject(nil) do |memo, v|    
     memo = v.deep_find(key) if v.respond_to?(:deep_find)  
     memo unless memo.nil? 
     end 
    end  
    end 
end