Last active
October 22, 2017 09:55
-
-
Save buren/6ba629ff7ff848e377ce660fab4e3807 to your computer and use it in GitHub Desktop.
Originally taken from: https://github.com/rohitpaulk/named_struct
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
class KeyStruct < Struct | |
def initialize(**keyword_args) | |
keyword_args.each do |key, value| | |
if members.include?(key) | |
self[key] = value | |
else | |
raise ArgumentError, "Unknown key struct member: #{key}" | |
end | |
end | |
end | |
end |
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
require 'spec_helper' | |
RSpec.describe KeyStruct do | |
it 'works with all arguments present' do | |
klass = KeyStruct.new(:name, :age) | |
instance = klass.new(name: 'buren', age: 28) | |
expect(instance.name).to eq('buren') | |
expect(instance.age).to eq(28) | |
end | |
it 'works with some arguments present' do | |
klass = KeyStruct.new(:name, :age) | |
instance = klass.new(name: 'buren') | |
expect(instance.name).to eq('buren') | |
expect(instance.age).to be_nil | |
end | |
it 'works with no arguments present' do | |
klass = KeyStruct.new(:name, :age) | |
instance = klass.new | |
expect(instance.name).to be_nil | |
expect(instance.age).to be_nil | |
end | |
it 'raises ArgumentError if passed unknown key' do | |
klass = KeyStruct.new(:name) | |
expect { klass.new(watman: 'buren') }.to raise_error(ArgumentError) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment