Question

I need to take a DSL like this:

defmodule SomeModule do
  use SomeMacros

  # sample shipping DSL
  rule is_north_america do
    calculate_shipping_cost_with usps
  end

  rule is_north_america and november_or_december do
    calculate_shipping_cost_with ups
  end

  rule is_south_america do
    calculate_shipping_cost_with fedex
  end

  rule is_somewhere_else do
    calculate_shipping_cost_with dhl
  end
end

And convert each call to the rule macro(which I already have defined) and have it define a function within SomeModule module. Like this:

def is_north_america_rule(Address[continent: "North America"] = address) do
  # do something
end 

I would like to use pattern matching on the parameters passed into the functions generated by the macros. I have seen how to define custom functions in macros but I am unsure as how to go about implementing pattern matching and guards in functions generated by macros.

Thanks in advance!

Was it helpful?

Solution

Here is an example of how you could achieve something similar:

https://gist.github.com/josevalim/7432084

I was going to add more information but I decided to provide a simple example and then answer any further question you may have. As a note though, try to make this rules DSL as simple as possible, if you see the macro code starting to get more and more complex, simply using a cond (explicitly) would be better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top