Created
June 24, 2010 22:58
-
-
Save jbr/452112 to your computer and use it in GitHub Desktop.
antonym_accessor
This file contains hidden or 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
class Module | |
def antonym_accessor(*args) | |
if 2 == args.length | |
from, to = args | |
define_method("#{to}?") { not send "#{from}?" } | |
define_method("#{to}=") {|val| send "#{from}=", ! val } | |
elsif 1 == args.length && args.first.is_a?(Hash) | |
args.first.each {|from, to| antonym_accessor from, to} | |
else | |
raise <<-EXCEPTION | |
antonym_accessor expects either | |
"antonym_accessor :from, :to" | |
or "antonym_accessor :from => :to" | |
EXCEPTION | |
end | |
end | |
end | |
class ExampleClass | |
def private?() @private end | |
def private=(p) @private = p end | |
antonym_accessor :private => :public | |
# or, if you prefer: | |
# antonym_accessor :private, :public | |
end | |
e = ExampleClass.new | |
e.private = false | |
e.public? #=> true | |
e.public = true | |
e.private? #=> false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment