跳至内容 跳至搜索

Active Support 参数过滤器

ParameterFilter 会在键与指定的过滤器匹配时,替换 Hash 类型对象中的值。

通过使用点表示法(例如 "credit_card.number")可以根据嵌套的键进行匹配。

如果给定一个 Proc 作为过滤器,那么 Hash 类型对象及其任何嵌套 Hashes 的键和值都会被传递给它。然后可以使用 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)

使用给定的过滤器创建实例。支持的过滤器类型有 StringRegexpProc。其他类型的过滤器将通过 to_s 被视为 String。对于 Proc 过滤器,键、值以及可选的原始哈希会被传递给块参数。

选项

  • :mask - 过滤时替换的对象。默认为 "[FILTERED]"

# File activesupport/lib/active_support/parameter_filter.rb, line 77
def initialize(filters = [], mask: FILTERED)
  @mask = mask
  compile_filters!(filters)
end

precompile_filters(filters)

预编译一组过滤器,这些过滤器否则会直接传递给 initialize。根据过滤器的数量和类型,预编译可以提高过滤性能,尤其是在无法保留 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 的值。

# File activesupport/lib/active_support/parameter_filter.rb, line 83
def filter(params)
  @no_filters ? params.dup : call(params)
end

filter_param(key, value)

返回给定键的过滤后的值。对于 Proc 过滤器,第三个块参数未被填充。

# File activesupport/lib/active_support/parameter_filter.rb, line 88
def filter_param(key, value)
  @no_filters ? value : value_for_key(key, value)
end