Created
August 9, 2016 00:11
-
-
Save kigster/31c323757ebeedbfa2ad26469ca0e18b to your computer and use it in GitHub Desktop.
This example demonstrates how to create Ruby Structs that use newer hash-style parameters, and are able to have default values for some of the properties. Raw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment