Ruby access propteries with dot-notation -


i'm trying build class used data structure storing values/nested values. want there 2 methods, get , set, accept dot-notated path recursively set or variables.

for example:

bag = parambag.new bag.get('foo.bar') # => nil bag.set('foo.bar', 'baz') bag.get('foo.bar') # => 'baz' 

the get method take default return value if value doesn't exist:

bag.get('foo.baz', false) # => false 

i initialize new parambag hash.

how manage in ruby? i've done in other languages, in order set recursive path, take value reference, i'm not sure how i'd in ruby.

this fun exercise still falls under "you should not this" category.

to accomplish want, openstruct can used slight modifications.

class parambag < openstruct   def method_missing(name, *args, &block)     if super.nil?       modifiable[new_ostruct_member(name)] = parambag.new     end       end end 

this class let chain many method calls , set number of parameters.

tested ruby 2.2.1

2.2.1 :023 > p = parambag.new  => #<parambag>  2.2.1 :024 > p.foo  => #<parambag>  2.2.1 :025 > p.foo.bar  => #<parambag>  2.2.1 :026 > p.foo.bar = {}  => {}  2.2.1 :027 > p.foo.bar  => {}  2.2.1 :028 > p.foo.bar = 'abc'  => "abc"  

basically, take get , set methods away , call methods normally.

i not advise this, instead suggest use openstruct acheive flexibility without going crazy. if find needing chain ton of methods , have them never fail, maybe take step backwards , ask "is right way approach problem?". if answer question resounding yes, parambag might perfect.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -