簡體   English   中英

如何重構此Ruby清理散列方法以使其更加慣用?

[英]How to refactor this Ruby sanitize hash method to make it more idiomatic?

此方法采用哈希並返回沒有敏感信息的新哈希。 它不會修改傳入的哈希。

有沒有更像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。

也許像這樣:

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標准修改哈希表,而不會造成重復。

  • 如在解決方案中那樣,為哈希中的每個密鑰迭代受保護的密鑰效率不高。 相反,只需遍歷受保護的密鑰。

  • 每次調用該方法時,生成受保護密鑰的數組效率低下。 在方法之外定義該數組。

在這些方面,以下更好:

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

還有一個:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM