Skip to content

Instantly share code, notes, and snippets.

@jbr
Created June 24, 2010 22:58
Show Gist options
  • Save jbr/452112 to your computer and use it in GitHub Desktop.
Save jbr/452112 to your computer and use it in GitHub Desktop.
antonym_accessor
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