Cristian Oliveira
Cristian Oliveira

Reputation: 770

Elixir: String Force encode UTF-8

I have a gem in ruby that does translations using google API and I am "translating" it to Elixir.

For example, I get from API some like this: api-data

And in Ruby today I do this:

  encoded = rawdata.force_encoding("UTF-8")

I would like to know if there is a way to "force_encode" (like Ruby does) but with Elixir?

UPDATE SOLUTION

I reached a solution based in your answers guys thanks a lot!

As Elixir handle it as binaries then that is the trick: I get the response body: body |> IO.iodata_to_binary ...

defmodule Request do
  alias Extract
  use HTTPotion.Base

  def process_url(url) do
    "https://translate.google.com/translate_a/" <> url
  end

  def process_response_body(body) do
    body |> IO.iodata_to_binary |> Extract.extract
  end
end

Here is entire code

Upvotes: 3

Views: 2742

Answers (1)

Jos&#233; Valim
Jos&#233; Valim

Reputation: 51369

You use force encoding in Ruby when the data is tagged as binary but really is UTF-8. In Elixir, they are both at the same time, because all strings are binaries, we don't tag them in anyway. In other words, you shouldn't need to force encoding.

However, if the data is not in UTF-8, then you need to find a way to convert it to UTF-8 in the first place.

Upvotes: 4

Related Questions