Class | OpenObject |
In: |
lib/facets/more/openobject.rb
|
Parent: | Hash |
OpenObject is similar to OpenStruct, but differs in a couple ways.
OpenObject is a subclass of Hash and can do just about everything a Hash can do, except that most public methods have been made protected and thus only available internally or via send. A small number, like each are still exposed publically though b/c of their importance.
OpenObject will also clobber any method for which a slot is defined. Even generally very important methods can be clobbered, like instance_eval. So be careful. OpenObject should be used in highly controlled scenarios. If you want to pass one off to an "unknown" rountine, it is best to convert it to a Hash first and convert it back to an OpenObject when finished. To facilitate this the method as_hash! is provided.
o = OpenObject.new(:a=>1,:b=>2) o.as_hash!{ |h| h.update(:a=>6) } o #=> #<OpenObject {:a=>6,:b=>2}>
Finally, unlike a regular Hash, all OpenObject‘s keys are symbols and all keys are converted to such using to_sym on the fly.
PUBLIC_METHODS | = | /(^__|^instance_|^object_|^\W|^as$|^send$|^class$|\?$)/ |
Inititalizer for OpenObject is slightly differnt than that of Hash. It does not take a default parameter, but an initial priming Hash as with OpenStruct. The initializer can still take a default block however. To set the degault value use ++default!(value)++.
OpenObject(:a=>1).default!(0)