Parsing External Data with DTOs: A Practical Guide
Learn to parse external data using DTOs in Ruby on Rails. Discover why they matter, when to use them, and how to implement them with practical examples.
Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!
Learn to parse external data using DTOs in Ruby on Rails. Discover why they matter, when to use them, and how to implement them with practical examples.
Comments
Maybe you could try Ruby 3.2 Data it will be much simpler
class Member < Data.define(:name) def self.build(json) JSON.parse(json).then{ new(*h.slice(self.members)) } end end
class Project < Data.define(:name, :budget, :members) def to_h super.tap{|h| h[:members] = h.delete(:members).map(&:to_h) end def self.build(json) JSON.parse(json).then{|h| h[:members] = h[:members].map{ Member.new(_1) } new(h) } end end
comples objects could could be better “mapped” when one have builder class instead of the function (to_json)
Thanks. Before that I’ve usually used Struct for that. The only important note is that we should not inherit from Struct or from Data. It creates an anonymous class in the ancestor chain making debuging difficult and also doesn’t work well with code reload. But this is a good add to the post.
```ruby class Project < Struct.new(:name) end Project2 = Struct.new(:name) do end
p Project.ancestors # => [Project, #<Class:0x000000010512c658>, Struct, Enumerable, Object, Kernel, BasicObject] p Project2.ancestors # => [Project2, Struct, Enumerable, Object, Kernel, BasicObject] ```
This is a good reminder to put in the post.
Post a comment