before_filter 中的 ApplicationController 怎么样
此模块方法应递归迭代哈希中的所有值并将其替换为块返回的值。
module RecurseHash
def recurse!(&blk)
__recurse(self, &blk) if block_given?
end
private
def __recurse(obj, &blk)
if obj.is_a? Array
obj = obj.map { |val| __recurse(val, &blk) }
elsif obj.is_a? Hash
obj.each_pair { |key, val| obj[key] = __recurse(val, &blk) }
else
obj = blk.call(obj)
end
obj
end
end
class Hash
include RecurseHash
end
class ApplicationController < ActionController::Base
before_filter :force_utf8
def force_utf8
params.recurse! do |val|
val.force_encoding 'UTF-8'
end
end
end
示例:
h = {:one=>1, :two=>2, :three=>[1, 2, 3, 4, 5], :four=>[6, {:a=>1, :b=>2}, 7]}
h.recurse! { |v| v * 2 }
# {:one=>2, :two=>4, :three=>[2, 4, 6, 8, 10], :four=>[12, {:a=>2, :b=>4}, 14]}
注意:如果该块没有返回任何内容,则该值将替换为nil。您可以使用它来过滤某些参数。