Skip to content

Instantly share code, notes, and snippets.

@minghz
Created April 17, 2020 05:41
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/13c70a8c757e34d3301f2d5b8ef257f2 to your computer and use it in GitHub Desktop.
Save minghz/13c70a8c757e34d3301f2d5b8ef257f2 to your computer and use it in GitHub Desktop.
Three Examples of DTOs in Ruby - Method 2: Hierarchical
#
# There are two classes here belonging to the same data transfer object
# They follow the first example, but are hierarcal. Meaning that the DTO called
# BirthdayCard has a sub-DTO called BirthdayCard::Template.
#
# It is possible to have more deeply nested hiearcies within
# BirthdayCard::Template depending on the use-case.
#
# Finally, if the DTO becomes overly-complex, i.e. say BirthdayCard had 3 layers
# of hiearchy, and more than one branch:
#
# - BirthdayCard::Message
# - BirthdayCard::Message::Text
# - BirthdayCard::Message::Signature
# - BirthdayCard::Template
# - BirthdayCard::Template::Title
# - BirthdayCard::Template::Picture
# ... etc
#
# It would be best to have a separate service (outside the Domain logic) assemble it
#
class BirthdayCard
attr_reader :from, :to, :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
joe_message = BirthdayCard::Message.new(text: 'Happy Birthday!', signature: 'joe_sig.jpeg')
jane_message = BirthdayCard::Message.new(text: 'Happy Birthday!', signature: 'jane_sig.jpeg')
BirthdayCard.new(from: 'me',
to: 'you',
messages: [joe_message, jane_message])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment