Skip to content

Instantly share code, notes, and snippets.

@tylerhunt
Created August 15, 2014 18:47
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 tylerhunt/63c0ff98aff2a5f584d2 to your computer and use it in GitHub Desktop.
Save tylerhunt/63c0ff98aff2a5f584d2 to your computer and use it in GitHub Desktop.
Void macro for Ruby
module Void
def void(method_name)
method = instance_method(method_name)
remove_method method_name
define_method(method_name) do |*args, &block|
method.bind(self).call(*args, &block).tap do |return_value|
raise TypeError, 'unexpected return value' unless return_value.nil?
end
end
method_name
end
end
describe Void do
subject {
Class.new do
extend Void
void def is_void
nil
end
void def is_not_void
true
end
end.new
}
specify do
expect(subject.is_void).to be_nil
end
specify do
expect { subject.is_not_void }
.to raise_error TypeError
end
end
@tylerhunt
Copy link
Author

Done as an experiment in writing a private-style macro for Ruby 2.1 (this won't work in earlier versions of Ruby where def returns nil instead of the method name).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment