How can I sanitize all params coming into a Sinatra app? How can I sanitize all params coming into a Sinatra app? json json

How can I sanitize all params coming into a Sinatra app?


Sanitize gem won't bundle, because this particular app runs in JRuby for some database reasons. Sanitize needs Nokogiri, which in turn needs Nokogumbo, and the latter just won't build in this JRuby environment.

seems wrong as Nokogiri works in JRuby (has a -java specific gem), try a bundle update nokogiri so that you get Sanitize to play nicely ...

So I tried doing a before filter in app.rb using Rack::Util's built in html escape method, but that blows up the app.

again, too bad. maybe post details on you gem versions and the failures you run into. although the preferred option, I believe, would be to get something that worked under MRI working under JRuby - thus I would try again to use Nokogiri.


Per Sinatra, there are 2 good ways of escaping. Both are mentioned on the website. http://www.sinatrarb.com/faq.html#escape_html

1) Using Rack. The op mentioned that it was blowing up the app. Could you please explain more? Meanwhile, to use the rack method, you can use the following code snippet. Once the param has been cleaned, you can use that.

cleanedParam = Rack::Utils.escape_html(params[:some_param_name])

2) Using Erubis gem. The gem is written in pure ruby. Setup the erubis gem as follows:

require 'erubis'set :erb, :escape_html => true

Once that is done, you can use erubis when outputing a template

erb :index


You can iterate through each of the parameters in the params hash and use Rack's escape_html method to escape HTML elements contained in each parameter.

params.each do |p, v|  params[p] = Rack::Utils.escape_html(v)end

The documentation for escape_html can be found here.