Created
August 15, 2014 18:47
-
-
Save tylerhunt/63c0ff98aff2a5f584d2 to your computer and use it in GitHub Desktop.
Void macro for Ruby
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
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 |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Done as an experiment in writing a
private
-style macro for Ruby 2.1 (this won't work in earlier versions of Ruby wheredef
returnsnil
instead of the method name).