diff --git a/lib/saxy/builder.ex b/lib/saxy/builder.ex index 508fc8f..5941e57 100644 --- a/lib/saxy/builder.ex +++ b/lib/saxy/builder.ex @@ -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 @@ -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( diff --git a/test/saxy/builder_test.exs b/test/saxy/builder_test.exs index 84c8ccc..1b47e6a 100644 --- a/test/saxy/builder_test.exs +++ b/test/saxy/builder_test.exs @@ -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