Get a sub string from module name

I have a module name Some.V1.CustomerModel

when I convert it into string it gives me this struture:

 Some.V1.CustomerModel  |> to_string()


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:


Is it possible to separate the Customer string from the module? like this:


Any suggestions?

1 Like

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} |> |> 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?


I have accomplish that to get the customer like this:

       Regex.replace(~r/Model/, name, "")
       "Customer" |> String.to_downcase()

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). :slight_smile:

I meant without double quotes like this customer. not an atom like this :customer.:slight_smile:

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. :slight_smile: