Created
April 17, 2020 05:39
-
-
Save minghz/2e9eb4af074b3b7d02d49728035a8b26 to your computer and use it in GitHub Desktop.
Three Examples of DTOs in Ruby - Method 3: Mutable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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