Skip to content

Instantly share code, notes, and snippets.

@ismaelga
Last active August 29, 2015 14:15
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 ismaelga/6f2a8b2b52e98c06e2ff to your computer and use it in GitHub Desktop.
Save ismaelga/6f2a8b2b52e98c06e2ff to your computer and use it in GitHub Desktop.
** (CompileError) test/script_test.exs:8: function content/0 undefined
(stdlib) lists.erl:1336: :lists.foreach/2
(stdlib) erl_eval.erl:657: :erl_eval.do_apply/6
(stdlib) erl_eval.erl:121: :erl_eval.exprs/5
defmodule Exredis.Script do
defmacro __using__(_) do
quote do
import Exredis.Script
end
end
defmacro defredis_script(name, file_path: file_path) do
quote do
{:ok, content} = File.read(unquote(file_path))
defredis_script(unquote(name), content)
end
end
defmacro defredis_script(name, script) do
quote do
@script_sha :crypto.hash(:sha, unquote(script))
def unquote(name)(client, keys \\ [], argv \\ []) do
query_args = [length(keys)] ++ keys ++ argv
case Exredis.query client, ["EVALSHA", @script_sha] ++ query_args do
<<"NOSCRIPT", _ :: binary>> ->
Exredis.query client, ["EVAL", unquote(script)] ++ query_args
reply -> reply
end
end
end
end
end
{:ok, content} = File.read("test/example_script.lua")
defredis_script(:return_one_file, content)
@chrismccord
Copy link

defmodule Exredis.Script do
  defmacro __using__(_) do
    quote do
      import Exredis.Script
    end
  end

  defmacro defredis_script(name, file_path: file_path) do
    {:ok, content} = File.read(file_path)
    quote do
      defredis_script(unquote(name), unquote(content))
    end
  end
  defmacro defredis_script(name, script) do
    quote do
      @script_sha :crypto.hash(:sha, unquote(script))
      def unquote(name)(client, keys \\ [], argv \\ []) do
        query_args = [length(keys)] ++ keys ++ argv
        case Exredis.query client, ["EVALSHA", @script_sha] ++ query_args do
          <<"NOSCRIPT", _ :: binary>> ->
            Exredis.query client, ["EVAL", unquote(script)] ++ query_args
          reply -> reply
        end
      end
    end
  end
end

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