Skip to content

Instantly share code, notes, and snippets.

@minghz
Created April 17, 2020 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minghz/2e9eb4af074b3b7d02d49728035a8b26 to your computer and use it in GitHub Desktop.
Save minghz/2e9eb4af074b3b7d02d49728035a8b26 to your computer and use it in GitHub Desktop.
Three Examples of DTOs in Ruby - Method 3: Mutable
#
# Mutable DTOs applies in case scenarios where the entire DTO may not be fully
# created in one go. Maybe it needs to be passed around several services and
# gradually enriched before being consumed.
#
# For example, passing around our birthday card to many friends to leave
# messages before finally delivering it to our recipient.
#
class BirthdayCard
attr_reader :from, :to
attr_accessor :messages
def initialize(from:, to:, messages: [])
@from = from
@to = to
@messages = messages
end
class Message
attr_reader :text, :signature
def initialize(text:, signature:)
@text = text
@signature = signature
end
end
end
# To create this DTO
birthday_card = BirthdayCard.new(from: 'me', to: 'you')
# Go find Joe in a party and ask him to write something on it
joe_message = BirthdayCard::Message.new(text: 'Happy Birthday!', signature: 'joe_sig.jpeg')
birthday_card.messages << joe_message
# Meet Jane somewhere else and she adds something too
jane_message = BirthdayCard::Message.new(text: 'Happy Birthday!', signature: 'jane_sig.jpeg')
birthday_card.messages << jane_message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment