Skip to content

Instantly share code, notes, and snippets.

@buren
Last active October 22, 2017 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buren/6ba629ff7ff848e377ce660fab4e3807 to your computer and use it in GitHub Desktop.
Save buren/6ba629ff7ff848e377ce660fab4e3807 to your computer and use it in GitHub Desktop.
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