Skip to content

Instantly share code, notes, and snippets.

@saraid
Last active April 19, 2016 23:22
Show Gist options
  • Save saraid/b60ce3fb1e806d26221a to your computer and use it in GitHub Desktop.
Save saraid/b60ce3fb1e806d26221a to your computer and use it in GitHub Desktop.
class Class
def method_invert(hash_or_existing, inverted = nil)
hash_or_existing = Hash[[[hash_or_existing, inverted]]] unless hash_or_existing.respond_to? :each_pair
hash_or_existing.each_pair do |existing, inverted|
define_method(inverted) do |*args, &block|
if self.respond_to?(existing)
self.send(existing, *args, &block)
else
self.instance_variable_get(existing)
end.!
end
end
end
end
class Foo
def initialize(one, two)
@one = one
@two = two
end
attr_reader :one
method_invert :one => :not_one,
:@two => :not_two
def with_param(bool)
bool
end
method_invert :with_param, :inverted_with_param
def with_block
yield
end
method_invert :with_block, :inverted_with_block
end
require 'test/unit'
class Stuff < Test::Unit::TestCase
def test_one_is_true
assert object.one
end
def test_two_is_not_a_method
assert_raise NoMethodError do object.two end
end
def test_not_one_is_false
refute object.not_one
end
def test_not_two_is_false
refute object.not_two
end
def test_with_param_is_param
assert object.with_param(true)
refute object.with_param(false)
end
def test_inverted_with_param_is_not_param
refute object.inverted_with_param(true)
assert object.inverted_with_param(false)
end
def test_with_block_is_block
assert object.with_block { true }
refute object.with_block { false }
end
def test_inverted_with_block_is_not_block
refute object.inverted_with_block { true }
assert object.inverted_with_block { false }
end
private
def object
Foo.new(true, true)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment