script
February 22, 2018, 6:20am
1
I have a module name Some.V1.CustomerModel
when I convert it into string it gives me this struture:
Some.V1.CustomerModel |> to_string()
"Elixir.Some.V1.CustomerModel"
I performed different functions on it and at the end if i do this :
"Elixir.Some.V1.CustomerModel" |> String.to_atom()
It gives me the original name without quotes
:
Some.V1.CustomerModel
Is it possible to separate the Customer
string from the module? like this:
customer
Any suggestions?
Thanks!
1 Like
Qqwy
February 22, 2018, 6:37am
2
The first part is easy: When you have a string, you can use functions in the String
module, like String.split
:
In this case, you could do:
res1 = Some.V1.CustomerModel |> to_string() |> String.split(".") |> List.last
# => "CustomerModel"
Now for removing the trailing word âModelâ, we need to use Regular Expressions. (If it was a leading word that was always the same, we could have used binary pattern matching, but thatâs not the case here)
~r{(\w+)Model\z} |> Regex.run(res1) |> List.last
# => "Customer"
However, your request is a rather weird one. Maybe a case of the X-Y problem ?
So: Why do you want to extract this single word from the module name? What do you want to accomplish by doing so?
4 Likes
script
February 22, 2018, 6:56am
3
I have accomplish that to get the customer like this:
Regex.replace(~r/Model/, name, "")
"Customer" |> String.to_downcase()
"customer"
The problem is converting this string back to customer
without quotes.
I need this to dynamically generate test cases. Because my controller code is almost same for every controller.
String.to_existing_atom
(or if you are reeeeeally careful then you can use String.to_atom
).
script
February 22, 2018, 5:49pm
5
I meant without double quotes like this customer
. not an atom like this :customer
.
The string âcustomerâ already doesnât have double quotes. The printed representation of a string has double quotes but the string itself doesnât.
For note, something like Some.V1.CustomerModel
is an atom, so if you want the string back as an atom, then the above calls is what you want.