Manually filter parameters in Rails

后端 未结 3 569
粉色の甜心
粉色の甜心 2020-12-09 02:11

How would I go about manually filtering a hash using my application\'s parameter filter?

I imagine it\'d go like this:

Rails.application.filter :pass         


        
3条回答
  •  無奈伤痛
    2020-12-09 02:33

    See the config/application.rb file, towards the end there is a line:

    config.filter_parameters += [:password]
    

    This way the "password" param will not be shown in logs, but you can still access the value normally.

    Edit

    It seem that have misunderstood your meaning of "filter" originally. As for the clarified issue, I have no idea on how to handle it the truly Rails way.

    Here is a brute force approach:

    1. Parse the query with CGI::parse(URI.parse(my_url_address_with_params).query) to get a hash of param/values (note: values are actually stored as an array; here is the discussion).
    2. Locate the parameters you want to filter out and replace values with literal *filtered*.
    3. Call Rails.logger.info (or debug) directly to log.

    Here is what you should dig into when relying on Rails magical classes and methods:

    In Rails 3 the code that does the trick seems to live in ActionDispatch::Http (ParameterFilter in particular, method `filtered_parameters'). The documentation is available at API Dock (or, to be honest, very little documentation). You can examine the sources to get an idea of how this works.

    My knowledge of Rails internals is not good enough to suggest anything else. I believe that someone with a better understanding of it might be of more help.

提交回复
热议问题