Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions lib/saxy/builder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,15 @@ end
defimpl Saxy.Builder, for: Any do
defmacro __deriving__(module, _struct, options) do
name = Keyword.fetch!(options, :name)
attribute_fields = Keyword.get(options, :attributes, [])

attribute_fields =
options
|> Keyword.get(:attributes, [])
|> Map.new(fn
field when is_atom(field) -> {field, field}
{field, attribute} -> {field, attribute}
end)

children_fields = Keyword.get(options, :children, [])

quote do
Expand All @@ -87,8 +95,13 @@ defimpl Saxy.Builder, for: Any do

attributes =
struct
|> Map.take(unquote(attribute_fields))
|> Enum.to_list()
|> Map.take(unquote(Map.keys(attribute_fields)))
|> Enum.map(fn {field, value} ->
case unquote(Macro.escape(attribute_fields)) do
%{^field => attribute} -> {attribute, value}
_ -> {field, value}
end
end)

children =
Enum.map(
Expand Down
10 changes: 10 additions & 0 deletions test/saxy/builder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ defmodule Saxy.BuilderTest do
}
end

defmodule DeliveryOption do
@derive {Saxy.Builder, name: "option", attributes: [:cost, :days, order_before: "order-before"]}
defstruct [:cost, :days, :order_before]
end

test "builds structs with renamed attributes" do
delivery_option = %DeliveryOption{cost: 300, days: 4, order_before: 18}
assert build(delivery_option) == {"option", [{"cost", "300"}, {"days", "4"}, {"order-before", "18"}], []}
end

@tag :property

property "number" do
Expand Down