2

此方法采用散列并返回不包含敏感信息的新散列。它不会修改传入的哈希值。

有没有更类似于 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

使用 Ruby 1.9.3、Sinatra(不是 Rails)而不使用 Active Record。

4

3 回答 3

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!将根据 Ruby 标准在不重复的情况下修改 Hash。

于 2013-11-12T19:24:59.163 回答
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
于 2013-11-12T19:31:34.797 回答
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)
于 2013-11-12T19:35:34.797 回答