RulEx.Encoding behaviour (RulEx v1.0.0) View Source
This behaviour defines how to translate RulEx expressions into any encoding formats your application may want/need, e.g. converting them into JSON values.
This is useful when you want to store RulEx expressions into database and/or if you want to transfer the rules over the wire to other services/systems that may need it.
Usage
A custom RulEx encoding mechanism can be defined by simply using RulEx.Encoding
,
and passing a module defining your encode and decode functions
defmodule MyApp.RulEx.Encoder do
use RulEx.Encoding, encoder: CustomModule
end
Alternatively the internal encoder can be passed as an option when using RulEx.Encoding
defmodule MyApp.RulEx.Encoder do
use RulEx.Encoding
def __encoder__, do: CustomModule
end
Using this module to build your encoder is useful as the generated encoder would do validation on the RulEx expressions being encoded or decoded by it.
Link to this section Summary
Callbacks
Given an encoded RulEx expression, decode it back into a RulEx expression. This function will yield an error if decoded value is an invalid RulEx expression, or if it fails to decode the provided value.
Exactly identical to RulEx.Encoding.decode/1
but raises RulEx.DecodeError
in case of errors.
Given a RulEx expression, encode it into any parsable value. This function will yield an error if given an invalid value in place of the RulEx expression, or if it fails to encode the provided expression.
Exactly identical to RulEx.Encoding.encode/1
but raises RulEx.EncodeError
in case of errors.
Link to this section Callbacks
Specs
Given an encoded RulEx expression, decode it back into a RulEx expression. This function will yield an error if decoded value is an invalid RulEx expression, or if it fails to decode the provided value.
Examples
iex> # Assuming the use of a JSON encoder
iex> encoded = "[\"|\",[\">\",[\"val\",\"number\",10],[\"var\",\"number\",\"x\"]],[\"=\",[\"val\",\"any\",10],[\"var\",\"any\",\"x\"]]]"
iex> expression = [:|,[:>, [:val, "number", 10], [:var, "number", "x"]],[:=, [:val, "any", 10], [:var, "any", "x"]]]
iex> {:ok, ^expression} = decode(encoded)
iex> {:error, _reason} = decode("[]")
Specs
Exactly identical to RulEx.Encoding.decode/1
but raises RulEx.DecodeError
in case of errors.
Specs
Given a RulEx expression, encode it into any parsable value. This function will yield an error if given an invalid value in place of the RulEx expression, or if it fails to encode the provided expression.
Examples
iex> # Assuming the use of a JSON encoder
iex> expression = [:|,[:>, [:val, "number", 10], [:var, "number", "x"]],[:=, [:val, "any", 10], [:var, "any", "x"]]]
iex> encoded = "[\"|\",[\">\",[\"val\",\"number\",10],[\"var\",\"number\",\"x\"]],[\"=\",[\"val\",\"any\",10],[\"var\",\"any\",\"x\"]]]"
iex> {:ok, ^encoded} = encode(expression)
iex> {:error, _reason} = encode([])
Specs
Exactly identical to RulEx.Encoding.encode/1
but raises RulEx.EncodeError
in case of errors.