We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Memoization in Elixir
almirsarajcic
0 comments
Copy link
Coming to Elixir from Ruby, you probably miss wonderful memoization syntax:
class Product
def info
@info ||= expensive_api_request
end
# ...
end
Every subsequent call to Product.info will use the in-memory value of the @info attribute.
We can achieve the same in Elixir in different ways, but one of the easiest is using the memoize package.
defmodule Product do
use Memoize
defmemo info(product_id) do
expensive_api_request(product_id)
end
end
There are more complex examples including expiry time, invalidation, etc., so make sure to check out the documentation: https://hexdocs.pm/memoize/readme.html.
copied to clipboard
Comments (0)
Sign in with GitHub to join the discussion