fceruti

fceruti

Inheritance in Elixir

I’m working on a cool library (news about that in a few weeks :smiley:), and there’s no sugar coating this: I really want to use inheritance.

I’m no Elixir n00b, at least not completely. I’ve enjoyed the functional paradigm shift very much, but in this particular case, I can’t help but feel like I’m jumping all kinds of hoops just to emulate what simple inheritance stuff would fit perfectly.

Let me describe the problem, then the best solution I’ve come up with, and I hope you can help me come up with a better one.

So, in this library, there’s lots of configuration to do. Most of this configuration will be written by the author of the library, lets call them starting points, and there are many of them. Users can use one of these starting points and just modify whatever they want to change and keep the rest. A config that uses a base “template” can also be a template for another config, and they would catch these config definitions in a cascade manner.

That’s probably the longest I’ve written about inheritance without mentioning it.

Right now I’ve got something like this:

defmodule Config do
  @callback __attr_value(atom(), atom()) :: atom()
  @optional_callback __attr_value: 2

  defmacro __using__(_opts) do
     quote do
        @behaviour Config

         def attr_value(category, item) do
           try do
               __MODULE__.__attr_value(category, item)
           rescue
              _e in [UndefinedFunctionError, FunctionClauseError] ->
                variables = __MODULE__.__info__(:attributes)
    
                if parent = Keyword.get(variables, :parent) do
                  parent.__attr_value(category, item)
                else
                  default_value(category, item)
                end
           end
         end
     end 
  end
end

defmodule BaseConfig do
   use Config

   def __attr_value(:category, :name), do: :my_value
   def __attr_value(:category, :picture), do: :my_picture
end
   
defmodule ChildConfig do
   use Config
   @parent BaseConfig

   def __attr_value(:category, :name), do: :another_value
end

It works, but I don’t know, I’m feeling uneasy with it.

What do you think? Have you seen this in the wild? Is there a better way?

Marked As Solved

dimitarvp

dimitarvp

Quick shot at this: why not use defdelegate in the derived (child) configs?

Also Liked

cmo

cmo

I presume you mean something more advanced than a module attribute?

defmodule ChildConfig do
   @behaviour MyConfig
   @delegate BaseConfig
   def attr_value(:category, :name), do: :child_name
   defdelegate attr_value(a, b), to: @delegate
end
fceruti

fceruti

Oh man, thanks this is awesome. I got lost in a sea of macros when the solution was so simple :slight_smile:

Thanks!

eksperimental

eksperimental

First, do not use Config as the name for your behaviour since it is a module in Elixir.

Then I would work with module attributes and do compile time checks.
What i usually do is create functions in the behaviour module that are called by default with the default implementations defined in __using__/1. Also look into how to play with òptions passed to this macro.
Then also make use of defoverridable/1 to let the user rewrite the default implementation.
You should be covered by all this.

krasenyp

krasenyp

This is what I’ve implemented numerous times and works well. Something similar is shown in the article Macro Madness: How to use `use` well - DockYard.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

Other popular topics Top

William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement