Skip to content

Instantly share code, notes, and snippets.

@polimorfico
Created November 14, 2012 21:18
Show Gist options
  • Save polimorfico/4074902 to your computer and use it in GitHub Desktop.
Save polimorfico/4074902 to your computer and use it in GitHub Desktop.
Force your params encoding in Rails

If you have problems with your params encodings, use a Rack middleware to encode them before rails params parsing code is executed.

First, build a class according to the signature of a rack middleware layer.

#lib/force_params_encoding.rb
class ForceParamsEncoding
  def initialize(app)
    @app = app
  end

  def call(env)
    @request = Rack::Request.new(env)
    params = @request.params
    params[:something] = params[:something].force_encoding("ISO-8859-1").encode("UTF-8")
    @app.call(env)
  end
end

Then register the middleware from application.rb.

#config/application.rb
config.middleware.insert_before ActionDispatch::ParamsParser, "ForceParamsEncoding"

And that's all! ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment