Active Support 參數篩選器
ParameterFilter
會替換 Hash
類型物件中的值,如果其金鑰符合指定的其中一個篩選器。
可以使用點符號,達成根據巢狀金鑰進行比對,例如 "credit_card.number"
。
如果篩選器是 proc,會將 Hash
類型以及任何巢狀 Hash
的各個金鑰和值傳遞給它。接著,可以使用像 String#replace
這樣的函式來變更值或金鑰。
# Replaces values with "[FILTERED]" for keys that match /password/i.
ActiveSupport::ParameterFilter.new([:password])
# Replaces values with "[FILTERED]" for keys that match /foo|bar/i.
ActiveSupport::ParameterFilter.new([:foo, "bar"])
# Replaces values for the exact key "pin" and for keys that begin with
# "pin_". Does not match keys that otherwise include "pin" as a
# substring, such as "shipping_id".
ActiveSupport::ParameterFilter.new([/\Apin\z/, /\Apin_/])
# Replaces the value for :code in `{ credit_card: { code: "xxxx" } }`.
# Does not change `{ file: { code: "xxxx" } }`.
ActiveSupport::ParameterFilter.new(["credit_card.code"])
# Reverses values for keys that match /secret/i.
ActiveSupport::ParameterFilter.new([-> (k, v) do
v.reverse! if /secret/i.match?(k)
end])
方法
- F
- N
- P
類別公用方法
new(filters = [], mask: FILTERED) 連結
使用已提供的篩選器建立執行個體。篩選器的支援類型為 String
、Regexp
和 Proc
。其他類型的篩選器會使用 to_s
視為 String
。對於 Proc
篩選器,會將金鑰、值和選擇的原始 hash 傳遞給區塊引數。
選項
-
:mask
- 篩選後取代物件。預設為"[FILTERED]"
。
precompile_filters(filters) 連結
預編譯篩選器陣列,否則會直接傳遞給初始化。依據篩選器的數量和類型,預編譯可以改善篩選效能,尤其是在無法保留 ParameterFilter
執行個體本身(但可以保留預編譯的篩選器)的情況下。
filters = [/foo/, :bar, "nested.baz", /nested\.qux/]
precompiled = ActiveSupport::ParameterFilter.precompile_filters(filters)
# => [/(?-mix:foo)|(?i:bar)/, /(?i:nested\.baz)|(?-mix:nested\.qux)/]
ActiveSupport::ParameterFilter.new(precompiled)
# File activesupport/lib/active_support/parameter_filter.rb, line 55 def self.precompile_filters(filters) filters, patterns = filters.partition { |filter| filter.is_a?(Proc) } patterns.map! do |pattern| pattern.is_a?(Regexp) ? pattern : "(?i:#{Regexp.escape pattern.to_s})" end deep_patterns = patterns.extract! { |pattern| pattern.to_s.include?("\\.") } filters << Regexp.new(patterns.join("|")) if patterns.any? filters << Regexp.new(deep_patterns.join("|")) if deep_patterns.any? filters end
執行個體公用方法
filter(params) 連結
若 params
的金鑰符合其中一個篩選器,則對其值進行遮罩。