I’m trying to use dry-transformer with dry-struct to take a JSON api response and transform it into a struct. Is there any “official” way to do this? The best way I could figure out was to override the self.new
method which I don’t love doing:
class MyStruct < Dry::Struct
class Transformer < Dry::Transformer::Pipe
import Dry::Transformer::HashTransformations
define! do
# ...
end
end
def self.new(attributes)
data = Transformer.new.call(attributes)
super(data)
end
end
You could write an instance method to do this but building structs is so common I like to have a helper for this.
module MyTransformations
extend Dry::Transformer::Registry
def self.struct(attributes, klass) = klass.new(**attributes)
end
class Transformer < Dry::Transformer::Pipe
import MyTransformations
define! do
struct MyStruct
end
end
Transformer.new(attributes)
The alternate way to do a one-off would be
class Transformer < Dry::Transformer::Pipe
define! do
build_struct
end
def build_struct(attributes)
MyStruct.new(**attributes)
end
end
1 Like
Interesting! So instead of having the Struct do the transformation, have the Transformer return a struct. I’ll try that out, thank you!