使用config.filter_parameters自定义过滤rails 3中的参数

我正在努力从Rails 2.3.11升级到3.0.10,并且无法转换ApplicationControllerfilter_parameter_logging 。 我想过滤某些参数,如果它们出现在类似:referrer标记的值中,也会对它们进行过滤。

我可以在我的application.rb获取过滤掉的常规参数

 config.filter_parameters += [:password, :oauth, ...] 

但我遇到的问题是我们也在filter_parameter_logging中传递的块。 它还会过滤掉任何看似url的值中的参数,因此http://example.com?password=foobar&oauth=123foo&page=2会被记录为http://example.com?password=[FILTERED]&oauth=[FILTERED]&page=2 。 我需要一种方法让rails既可以过滤指定的参数,也可以过滤掉其他值中的参数,比如上面的url。

这是filter_parameter_logging中的样子:

 FILTER_WORDS = %{password oauth email ...} FILTER_WORDS_REGEX = /#{FILTER_WORDS.join("|")}/i #Captures param in $1 (would also match things like old_password, new_password), and value in $2 FILTER_WORDS_GSUB_REGEX = /((?:#{FILTER_WORDS.join("|")})[^\/?]*?)(?:=|%3D).*?(&|%26|$)/i filter_parameter_logging(*FILTER_WORDS) do |k,v| begin # Bail immediately if we can next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D")) #Filters out values for params that match v.gsub!(FILTER_WORDS_GSUB_REGEX) do "#{$1}=[FILTERED]#{$2}" end rescue Exception => e logger.error e end end 

有没有办法使用config.filter_parameters中的config.filter_parameters以这种方式进行rails过滤? 我似乎无法找到有关如何在rails 3中自定义过滤的任何好文档。

弄清楚了。 你可以将lambda语句传递给config.filter_parameters ,所以在我将参数添加到filter之后,我现在有了这个:

 config.filter_parameters << lambda do |k,v| begin # Bail immediately if we can next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D")) #Filters out values for params that match v.gsub!(FILTER_WORDS_GSUB_REGEX) do "#{$1}=[FILTERED]#{$2}" end rescue Exception => e logger.error e end end