Skip to content

Instantly share code, notes, and snippets.

@tylerflint
Created March 15, 2014 16:41
Show Gist options
  • Save tylerflint/9570175 to your computer and use it in GitHub Desktop.
Save tylerflint/9570175 to your computer and use it in GitHub Desktop.
Elixir dsl/macro discovery

dsl

In this experiment, I'm attempting to create a dsl that will allow me to

  • execute a dsl in the module definition
  • store data in the module (similar to Ruby's class instance variables)
  • fetch the data stored in the module from within a function defined inside of that module

Here is an example module that uses the dsl:

defmodule Foozle.Doozle do
  
  use Foozle.Dsl

  set :foo, "bar"
  set :baz, "boa"

  def test do
    IO.puts "foo: #{get(:foo)}"
    IO.puts "baz: #{get(:baz)}"
  end

end

using

For the first experiment I attempted to define the set/2 & get/1 methods inside the using block itself.

This worked! Almost :) I learned two things:

  • a function can be defined within the using macro
  • that function cannot be used until the module is compiled into erlang bytecode (ie: NOT during the macro evaluation)
defmodule Foozle.Dsl do
  
  defmacro __using__(_opts) do

    quote do

      def set(key, val) do
        IO.puts "set(#{key}, #{val}"      
      end

      def get(_key) do
        "whatev"
      end

    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment