Hi Friends, how can convert a block code to string in elixir?
For example, I have a list like this:
list = [
{:phoenix, "~> 1.6.6"},
{:sourceror, "~> 0.11.1"},
{:mishka_installer, git: "https://github.com/mishka-group/mishka_installer.git"}
]
now I want to convert it like this:
"""
[
{:phoenix, "~> 1.6.6"},
{:sourceror, "~> 0.11.1"},
{:mishka_installer, git: "https://github.com/mishka-group/mishka_installer.git"}
]
"""
It is not a `ex` file or sth which I can be able to use `File.read`, it is like a query from database and I need to convert.
I tried to use `Macro.to_string(quote(do: list))`, but it converts the list like this
```elixir
iex(10)> Macro.to_string(quote(do: list))
"list"
not the list of tuples.
Thank you in advance
7stud
May 18, 2022, 3:39pm
2
Kernel.inspect:
iex(12)> list = [
...(12)> {:phoenix, "~> 1.6.6"},
...(12)> {:sourceror, "~> 0.11.1"},
...(12)> {:mishka_installer, git: "https://github.com/mishka-group/mishka_installer.git"}
...(12)> ]
[
phoenix: "~> 1.6.6",
sourceror: "~> 0.11.1",
mishka_installer: [
git: "https://github.com/mishka-group/mishka_installer.git"
]
]
iex(13)> Kernel.inspect list
"[phoenix: \"~> 1.6.6\", sourceror: \"~> 0.11.1\", mishka_installer: [git: \"https://github.com/mishka-group/mishka_installer.git\"]]"
iex(14)>
Depending on what you plan to do with the string, you might also consider erlang’s term_to_binary/1,2
.
1 Like
Be aware though, that inspect
does produce a readable form of the data, but it’s not guaranteed to be executable/not failing code.
1 Like
Thank both of you @7stud @LostKobrakai .
Actually, I am using this lib: GitHub - doorgan/sourceror: Utilities to manipulate Elixir source code and I need to convert a list of tuples to string.
like this:
"""
[
{:phoenix, "~> 1.6.6"},
{:sourceror, "~> 0.11.1"},
{:mishka_installer, git: "https://github.com/mishka-group/mishka_installer.git"}
]
"""
|> Sourceror.parse_string!()
Based on its documents, parse_string
supports a binary block of code
Update:
7stud:
Kernel.inspect:
It changes the list of tuples, I know it is both of the are same
[
phoenix: "~> 1.6.6",
sourceror: "~> 0.11.1",
mishka_installer: [
git: "https://github.com/mishka-group/mishka_installer.git"
]
]
==
[
{:phoenix, "~> 1.6.6"},
{:sourceror, "~> 0.11.1"},
{:mishka_installer, git: "https://github.com/mishka-group/mishka_installer.git"}
]
but I do not know it is going to be a problem for the thing I need?
If you have an opinion, I would be very grateful if you could tell me
Thank you in advance.