How to save map (pulled from JSON) as attribute of module?

At this week i start working on porting this Python open source library for Elixir and I ran into some difficulties, because i’m beginner in Elixir.

In Python we can save data (from JSON file) in self.data and work with them.

class Address(object):
    def __init__(self, locale='en'):
        self.locale = locale
        self.data = pull('address.json', self.locale)

     def get_city(self):
         return self.data["city"]

At this moment i use following method:

  def name(gender) do
    {:ok, names} = Machiavelli.pull("personal", "names", :en)
    Enum.random(names[gender])
  end

  def surname(gender) do
    {:ok, surnames} = Machiavelli.pull("personal", "surnames", :en)
    Enum.random(surnames[gender])
  end

but it is not good, because we pull data from json after every calling of function

When must be something like:

  def name(gender) do
    {:ok, names} = Machiavelli.data["names"][gender]
    names |> Enum.random
  end

  def surname(gender) do
    {:ok, surnames} = Machiavelli.data["surnames"][gender]
    surnames |> Enum.random
  end

So, how i can store the data like in example above?

Project located here.

1 Like

Module attributes can be used only at compile time. To store state you might want to try a GenServer or an Agent (abstraction over genserver).

2 Likes

Thank you. Agent is suitable for me.

1 Like

Do keep in mind that a lot of patterns you’re used too coming from python are going to look very different, or require totally re-thinking the solution in Elixir. If you find yourself often using agents in regular functions frequently to store information you may want to look at the problem as a whole to find a more functional approach.

1 Like

Totally agree. Thanks.

1 Like