Reputation: 166
I want my app to response with body utf-8 and iso-8859-1 encoded per requests with Accept-Charset="utf-8" or Accept-Charset="iso-8859-1". The response body is always JSON.
In my controller, when I doing this
render(json: data, status: :created)
It response with Content-Type="application/json; charset=utf-8" as well.
But how to make a response with body iso-8859-1 encoded when request Accept-Charset="iso-8859-1"?
Upvotes: 1
Views: 418
Reputation: 134
In order to do this, you can use the method force_encoding
and encoding
for example
data = {'name'=>'raghav'}.to_json
data.encoding #This would return what encoding the value as #<Encoding:UTF-8>
new_data = data.force_encoding('ISO-8859-1') #This would force the encoding
new_data.encoding #<Encoding:ISO-8859-1>
Also to do this on the specific case you can always read the request.headers
hash to determine the encoding.
There is also another method called encode
the main difference between these are force_encoding
changes the way string is being read from bytes, and encode
changes the way string is written without changing the output (if possible)
Upvotes: 1