Sha256: 335592dad22201938857f836555c4975524479764d5ade864862145bd84e3036

Contents?: true

Size: 1.54 KB

Versions: 8

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module ConvenientService
  module Support
    module Copyable
      ##
      # @example
      #   person = Person.new('John', 'Doe', age: 42, gender: :male) do |p|
      #     puts p
      #   end
      #
      #   copy = person.copy
      #   copy = person.copy(overrides: {args: ['Jane']})
      #   copy = person.copy(overrides: {args: {0 => 'Jane'}})
      #   copy = person.copy(overrides: {kwargs: {age: 18}})
      #   copy = person.copy(overrides: {block: proc { |p| print p }})
      #
      # @internal
      #   NOTE: Inline logic instead of private methods is used intentionally in order to NOT pollute the public interface.
      #   NOTE: This method is NOT likely to be ever changed, that is why inline logic is preferred over command classes in this particular case.
      #
      #   NOTE: The `respond_to` solution was slower by 16%. Check this file history to review the previous implementation. Use the `empty_service` benchmark to compare.
      #
      def copy(overrides: {})
        defaults = {args: {}, kwargs: {}}

        ##
        # IMPORTANT: Do not mutate `overrides`.
        #
        overrides = defaults.merge(overrides)

        args =
          case overrides[:args]
          when ::Array then overrides[:args]
          when ::Hash then Utils::Array.merge(to_arguments.args, overrides[:args])
          end

        kwargs = to_arguments.kwargs.merge(overrides[:kwargs])
        block = overrides[:block] || to_arguments.block

        self.class.new(*args, **kwargs, &block)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
convenient_service-0.19.1 lib/convenient_service/support/copyable.rb
convenient_service-0.19.0 lib/convenient_service/support/copyable.rb
convenient_service-0.18.0 lib/convenient_service/support/copyable.rb
convenient_service-0.17.0 lib/convenient_service/support/copyable.rb
convenient_service-0.16.0 lib/convenient_service/support/copyable.rb
convenient_service-0.15.0 lib/convenient_service/support/copyable.rb
convenient_service-0.14.0 lib/convenient_service/support/copyable.rb
convenient_service-0.13.0 lib/convenient_service/support/copyable.rb