Is there any library with similar functionality like mapstruct
I looked at that page, but still don’t understand what it does. Can you give a short description of what you are looking for?
map or merge two object
struct A
name : String
end
struct B
name : String
end
a = A.new "foo"
b : B = mapper.map(a)
puts b # {name: "foo"}
b.name = "bar"
mapper.merge(a, b)
puts a # {name: "bar"}
I don’t think there is a shard for that.
You could quite easily do something like this with macros, though:
record A, name : String
record B, name : String
class Mapper(T)
def self.map(x : U) forall U
{% begin %}
T.new(
{% for ivar in T.instance_vars %}
{{ ivar.name }}: x.{{ ivar.name }},
{% end %}
)
{% end %}
end
end
a = A.new "foo"
b = Mapper(B).map(a) # => B(@name="foo")
4 Likes