How to change the default value of a Struct attribute?

后端 未结 6 1388
孤城傲影
孤城傲影 2020-12-17 07:43

According to the documentation unset attributes of Struct are set to nil:

unset parameters default to nil.

Is it po

6条回答
  •  自闭症患者
    2020-12-17 08:34

    I think that the override of the #initialize method is the best way, with call to #super(*required_args).

    This has an additional advantage of being able to use hash-style arguments. Please see the following complete and compiling example:

    Hash-Style Arguments, Default Values, and Ruby Struct

    # This example demonstrates how to create Ruby Structs that use
    # newer hash-style parameters, as well as the default values for
    # some of the parameters, without loosing the benefits of struct's
    # implementation of #eql? #hash, #to_s, #inspect, and other
    # useful instance methods.
    #
    # Run this file as follows
    #
    # > gem install rspec
    # > rspec struct_optional_arguments.rb --format documentation
    #
    class StructWithOptionals < Struct.new(
        :encrypted_data,
        :cipher_name,
        :iv,
        :salt,
        :version
        )
    
        VERSION = '1.0.1'
    
        def initialize(
            encrypted_data:,
            cipher_name:,
            iv: nil,
            salt: 'salty',
            version: VERSION
            )
            super(encrypted_data, cipher_name, iv, salt, version)
        end
    end
    
    require 'rspec'
    RSpec.describe StructWithOptionals do
        let(:struct) { StructWithOptionals.new(encrypted_data: 'data', cipher_name: 'AES-256-CBC', iv: 'intravenous') }
    
        it 'should be initialized with default values' do
            expect(struct.version).to be(StructWithOptionals::VERSION)
        end
    
        context 'all fields must be not null' do
            %i(encrypted_data cipher_name salt iv version).each do |field|
                subject { struct.send(field) }
                it field do
                    expect(subject).to_not be_nil
                end
            end
        end
    end
    

提交回复
热议问题