feat: add template for constant values
This commit is contained in:
parent
d6dad83013
commit
cb3455bf47
3 changed files with 54 additions and 0 deletions
|
@ -17,6 +17,13 @@ defmodule Smokestack.Dsl.Template do
|
|||
def choose(options, mapper \\ nil) when is_mapper(mapper),
|
||||
do: %Template.Choose{options: options, mapper: mapper}
|
||||
|
||||
@doc """
|
||||
Select a constant value
|
||||
"""
|
||||
@spec constant(element, mapper) :: Template.t()
|
||||
def constant(value, mapper \\ nil) when is_mapper(mapper),
|
||||
do: %Template.Constant{value: value, mapper: mapper}
|
||||
|
||||
@doc """
|
||||
Cycle sequentially between a list of options.
|
||||
"""
|
||||
|
|
16
lib/smokestack/template/constant.ex
Normal file
16
lib/smokestack/template/constant.ex
Normal file
|
@ -0,0 +1,16 @@
|
|||
defmodule Smokestack.Template.Constant do
|
||||
@moduledoc false
|
||||
defstruct value: nil, mapper: nil
|
||||
|
||||
@type t :: %__MODULE__{value: any, mapper: Smokestack.Template.mapper()}
|
||||
|
||||
defimpl Smokestack.Template do
|
||||
def init(constant), do: constant
|
||||
|
||||
def generate(constant, _, _) when is_function(constant.mapper, 1),
|
||||
do: constant.mapper(constant.value)
|
||||
|
||||
def generate(constant, _, _),
|
||||
do: constant.value
|
||||
end
|
||||
end
|
31
test/smokestack/template/constant.exs
Normal file
31
test/smokestack/template/constant.exs
Normal file
|
@ -0,0 +1,31 @@
|
|||
defmodule Smokestack.Template.ChooseTest do
|
||||
@moduledoc false
|
||||
use ExUnit.Case, async: true
|
||||
alias Smokestack.{Template, Template.Constant}
|
||||
|
||||
describe "Smokestack.Template.init/1" do
|
||||
test "it doesn't do anything" do
|
||||
constant = %Constant{value: 1, mapper: &Function.identity/1}
|
||||
|
||||
assert ^constant = Template.init(constant)
|
||||
end
|
||||
end
|
||||
|
||||
describe "Smokestack.Template.generate/3" do
|
||||
test "it returns the same value" do
|
||||
value =
|
||||
%Constant{value: 1}
|
||||
|> Template.generate(nil, nil)
|
||||
|
||||
assert value == 1
|
||||
end
|
||||
|
||||
test "it can map the chosen value" do
|
||||
value =
|
||||
%Constant{value: 1, mapper: &(&1 * 3)}
|
||||
|> Template.generate(nil, nil)
|
||||
|
||||
assert value == 3
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue