0

我无法在我的用户模型中获取以下方法来处理我从 LinkedIn 获取的用于用户登录的哈希('auth'):

def self.deep_get auth, *fields
    auth.inject(auth) { |acc, e| acc[e] if acc }
end

当我使用omniauth/linkedin gem 创建用户时,我稍后会在我的用户模型中调用“deep_get”方法。但是,它为我知道不是 nil 的 provider/uid/headline/email 用户字段返回 nil 值。

我将 first_name 和 last_name 字段作为示例,因为这种方法有效(不返回 nil 值),但是(据我所知)错误的样式/异常处理。关于为什么我的 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
4

1 回答 1

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
于 2012-09-17T14:17:10.970 回答