Created
October 19, 2010 09:21
-
-
Save akzhan/633906 to your computer and use it in GitHub Desktop.
How to use hash as getters and setters
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 PropertyHash < Hash | |
def method_missing(name, *args, &block) | |
return self[name.to_s] if include?(name.to_s) && args.size == 0 | |
return !!self[$1] if name.to_s =~ /^(.+)\?$/ && include?($1) && args.size == 0 | |
if name.to_s =~ /^(.+)\=$/ && include?($1) && args.size == 1 | |
self[$1] = args.first | |
return | |
end | |
super | |
end | |
def respond_to?(name) | |
return true if include?(name.to_s) | |
return true if name.to_s =~ /^(.+)[\?\=]$/ && include?($1) | |
super | |
end | |
end | |
class YourModel | |
attr_accessor :access | |
def initialize | |
@access = PropertyHash.new | |
end | |
end | |
def assert(msg = nil) | |
raise "Assertion failed: #{msg || 'Unknown'}" unless yield | |
end | |
obj = YourModel.new | |
obj.access['fault'] = :yes | |
assert('fault getter') do | |
obj.access.fault == :yes | |
end | |
assert('fault test') do | |
obj.access.fault? | |
end | |
assert('fault setter') do | |
obj.access.fault = :no | |
obj.access.fault == :no | |
end | |
assert('responds to getter') do | |
obj.access.respond_to?(:fault) | |
end | |
assert('responds to setter') do | |
obj.access.respond_to?(:fault=) | |
end | |
assert('responds to test') do | |
obj.access.respond_to?(:fault?) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment