Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lujanfernaud/53e54eb14a1d671a27374f3aa72afaa7 to your computer and use it in GitHub Desktop.
Save lujanfernaud/53e54eb14a1d671a27374f3aa72afaa7 to your computer and use it in GitHub Desktop.
Ruby: Immutable Value Object with Struct

Ruby: Immutable Value Object with Struct

Freezing the initializer after passing the args to super makes the object immutable.

# frozen_string_literal: true

# Freezing the initializer after passing the args to `super` makes the object immutable.
#
# Example:
#
#   require 'value_object'
#
#   ForcePullData = Struct.new(:repository_name, :site_id, keyword_init: true) do
#     include ValueObject
#   end
#
#   data = ForcePullData.new(repository_name: 'sandbox', site_id: 'site-id')
#
#   > data.repository_name
#   => "sandbox"
#
#   > data.repository_name = "plaything"
#   FrozenError: can't modify frozen ForcePullData:
#   #<struct ForcePullData repository_name="sandbox", site_id="site-id">
module ValueObject
  def initialize(**args)
    super(args)
    freeze
  end
end

This trick comes from Polished Ruby Programming by Jeremy Evans.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment