如何重构这个Ruby sanitize哈希方法以使其更具惯用性?

时间:2013-11-12 19:14:19

标签: ruby sinatra hashtable ruby-1.9.3

此方法接受哈希并返回没有敏感信息的新哈希。它不会修改传入的哈希值。

是否有更像Ruby的惯用方法呢?

def sanitize hash
  new_hash = hash.dup
  protected_keys = [ :password, 'password', :confirmation, 'confirmation' ]

  new_hash.each do |k,v|
    if protected_keys.include?( k ) && ! v.blank?
      new_hash[ k ] = 'xxxxxxxxx'
    end
  end

  new_hash
end

使用Active Record在Ruby 1.9.3,Sinatra(不是Rails)和 中工作。

3 个答案:

答案 0 :(得分:3)

也许是这样的:

class Hash
  def sanitize(*keys)
    new_hash = self.dup
    new_hash.each do |k,v| 
      if keys.include?(k) && ! v.empty?
        new_hash[k] = 'xxxxxxxxxx'
      end
    end
  end

  def sanitize!(*keys)
    self.each do |k,v|
      if keys.include?(k) && ! v.empty?
        self[k] = 'xxxxxxxxxx'
      end
    end
  end
end

然后你可以打电话

hash = {password: "test", name: "something"}
sanitized_hash = hash.sanitize(:password, 'password', :confirmation, 'confirmation')

然后sanitize!将修改Hash,而不会按照Ruby标准重复。

答案 1 :(得分:2)

  • 在解决方案中迭代哈希中每个密钥的受保护密钥是低效的。相反,只需遍历受保护的密钥。

  • 每次调用方法时生成受保护密钥数组都是低效的。在方法之外定义该数组。

以下在这些方面更好:

ProtectedKeys = %w[password confirmation]
def sanitize hash
  new_hash = hash.dup
  ProtectedKeys.each do |k| [k, k.to_sym].each do |k|
    new_hash[k] = "xxxxxxxxx" if new_hash.key?(k) and new_hash[k].present?
  end end
  new_hash
end

答案 2 :(得分:1)

还有一个:

def sanitize(params)
  protected_keys = %(password confirmation)
  replacement = 'xxxxxx'
  new_params = params.dup
  new_params.each_key {|key| new_params[key] = replacement if protected_keys.include?(key.to_s)}
end

test_hash = {
  name: 'Me',
  password: 'secret',
  address: 'Here',
  confirmation: 'secret'
}
puts sanitize(test_hash)