Skip to content

Instantly share code, notes, and snippets.

@roowe
Created March 8, 2016 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roowe/1f0a9dccb42f5ce2642e to your computer and use it in GitHub Desktop.
Save roowe/1f0a9dccb42f5ce2642e to your computer and use it in GitHub Desktop.
Erlang共享变量一种访问方式
-module(constant).
-export([compile/2]).
compile(Mod, KVList) ->
Bin = makes(Mod, KVList),
code:purge(Mod),
{module, Mod} = code:load_binary(Mod, atom_to_list(Mod) ++ ".erl", Bin),
ok.
makes(Module, KVList) ->
{ok, Module, Bin} = compile:forms(forms(Module, KVList),
[verbose, report_errors]),
Bin.
forms(Module, KVList) ->
[erl_syntax:revert(X) || X <- term_to_abstract(Module, KVList)].
term_to_abstract(Module, KVList) ->
ModuleName = erl_syntax:attribute(
erl_syntax:atom(module),
[erl_syntax:atom(Module)]),
Export = erl_syntax:attribute(
erl_syntax:atom(export),
[erl_syntax:list(
[erl_syntax:arity_qualifier(
erl_syntax:atom(K),
erl_syntax:integer(0)) || {K, _} <- KVList])]),
Functions = [erl_syntax:function(
erl_syntax:atom(K),
[erl_syntax:clause([], none, [erl_syntax:abstract(V)])]) || {K, V} <- KVList],
[ModuleName, Export | Functions].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment