Skip to content

Instantly share code, notes, and snippets.

@buren buren/key_struct.rb
Last active Oct 22, 2017

Embed
What would you like to do?
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
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
You can’t perform that action at this time.