Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lujanfernaud/53e54eb14a1d671a27374f3aa72afaa7 to your computer and use it in GitHub Desktop.

Select an option

Save lujanfernaud/53e54eb14a1d671a27374f3aa72afaa7 to your computer and use it in GitHub Desktop.

Revisions

  1. lujanfernaud revised this gist Jul 16, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion ruby_immutable_value_object_with_struct.md
    Original file line number Diff line number Diff line change
    @@ -31,4 +31,4 @@ module ValueObject
    end
    ```

    This trick comes from [Polished Ruby Programming](https://www.amazon.com/Polished-Ruby-Programming-maintainable-high-performance-ebook/dp/B093TH9P7C) by @jeremyevans.
    This trick comes from [Polished Ruby Programming](https://www.amazon.com/Polished-Ruby-Programming-maintainable-high-performance-ebook/dp/B093TH9P7C) by [Jeremy Evans](https://github.com/jeremyevans).
  2. lujanfernaud revised this gist Jul 16, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion ruby_immutable_value_object_with_struct.md
    Original file line number Diff line number Diff line change
    @@ -31,4 +31,4 @@ module ValueObject
    end
    ```

    This trick comes from [Polished Ruby Programming](https://www.amazon.com/Polished-Ruby-Programming-maintainable-high-performance-ebook/dp/B093TH9P7C) by Jeremy Evans.
    This trick comes from [Polished Ruby Programming](https://www.amazon.com/Polished-Ruby-Programming-maintainable-high-performance-ebook/dp/B093TH9P7C) by @jeremyevans.
  3. lujanfernaud created this gist Jul 16, 2021.
    34 changes: 34 additions & 0 deletions ruby_immutable_value_object_with_struct.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    # Ruby: Immutable Value Object with Struct

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

    ```rb
    # 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](https://www.amazon.com/Polished-Ruby-Programming-maintainable-high-performance-ebook/dp/B093TH9P7C) by Jeremy Evans.