inject方法从哈希中检索数据

时间:2012-09-17 14:02:17

标签: ruby-on-rails

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

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

我稍后在我的用户模型中调用'deep_get'方法,因为我使用omniauth / linkedin gem创建了一个用户。但是,它为提供者/ uid /标题/电子邮件用户字段返回nil值,我知道这些字段不是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

1 个答案:

答案 0 :(得分: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