Default Ruby accessor method?
-
10-07-2019 - |
Question
Is there a default method or class accessor that I can add to a Ruby class that get called if a accessor (Ruby like property) doesn't exit? I can then write some custom code to reply from like a array list read from a database where the value can be accessed like a accessor without me writing the accessor code (since if read from a database its unknown).
Using Ruby MRI 1.9
Thank you!
Solution
Yes, it's called method_missing
; it gets called whenever an undefined method is used. You can use it to add or emulate any method you want, including accessors.
For example, if you throw this on a Hash
you can treat the contents of the hash as properties:
h = {}
def h.method_missing(*args)
if args.length == 1
self[args[0]]
elsif args.length == 2 and args[0].to_s =~ /^(.*)=$/
self[$1.intern] = args[1]
else
super
end
end
let's you write:
h.bob = "Robert"
and
if h.bill == "William" ...
and so on in addition to the more normal h[:bob] = ...
style.