Default Ruby Access Method?

Is there a default method or a cool accessory that I can add to the Ruby class, which is called if the accessor (Ruby like property) does not exit? Then I can write some custom code for the answer, for example, as a list of arrays read from the database, where access to this value can be obtained, for example, through an accessory, without me writing an access code (because if read from an unknown database).

Using Ruby MRI 1.9

Thanks!

+4
source share
1 answer

Yes, it is called method_missing ; it is called whenever the undefined method is used. You can use it to add or emulate any method you want, including accessors.

For example, if you selected this on 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 you write:

 h.bob = "Robert" 

and

 if h.bill == "William" ... 

etc. in addition to the more normal style h[:bob] = ...

+10
source

All Articles