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!
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
Hashyou can treat the contents of the hash as properties:let’s you write:
and
and so on in addition to the more normal
h[:bob] = ...style.