Skip to content

Instantly share code, notes, and snippets.

@karlentwistle
Created April 30, 2015 18:49
Show Gist options
  • Save karlentwistle/79037921defd96efacf7 to your computer and use it in GitHub Desktop.
Save karlentwistle/79037921defd96efacf7 to your computer and use it in GitHub Desktop.
Negator Play
require 'rspec'
module Negator
def negate(method_name, as:)
if instance_methods.include?(method_name)
define_method(as) do
!send(method_name)
end
end
if singleton_methods.include?(method_name)
define_singleton_method (as) do
!send(method_name)
end
end
end
end
class InstanceMethodTester
extend Negator
def verified; true; end
negate :verified, as: :unverified
end
class ClassMethodTester
extend Negator
def self.verified; true; end
negate :verified, as: :unverified
end
class MixedTester
extend Negator
def self.verified; true; end
def verified; true; end
negate :verified, as: :unverified
end
RSpec.describe "negator" do
context 'instance method' do
it 'negates to falsy' do
expect(InstanceMethodTester.new.unverified).to eql(false)
end
it 'responds to new method signature' do
expect(InstanceMethodTester.new.respond_to?(:unverified)).to eql(true)
end
it 'does not respond to class method' do
expect(InstanceMethodTester.respond_to?(:unverified)).to eql(false)
end
end
context 'class method' do
it 'negates to falsy' do
expect(ClassMethodTester.unverified).to eql(false)
end
it 'responds to new method signature' do
expect(ClassMethodTester.respond_to?(:unverified)).to eql(true)
end
it 'does not respond to instance method' do
expect(ClassMethodTester.new.respond_to?(:unverified)).to eql(false)
end
end
context 'mixed method' do
it 'negates class method' do
expect(MixedTester.unverified).to eql(false)
end
it 'negates instance method' do
expect(MixedTester.new.unverified).to eql(false)
end
it 'negated class method responds to new method signature' do
expect(MixedTester.new.respond_to?(:unverified)).to eql(true)
end
it 'negated instance method responds to new method signature' do
expect(MixedTester.respond_to?(:unverified)).to eql(true)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment