Add arbitary levels to an OpenStruct - OpenStruct#add


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # Ex:
  2. # > foo = OpenStruct.new
  3. # > foo.add :bar
  4. # > foo.bar.a = 10
  5. # > foo.bar.a
  6. # => 10
  7. # > foo.add 'bar.baz.bax'
  8. # > foo.bar.baz.bax.something = 100
  9. # > foo.bar.baz.bax.something
  10. # => 100
  11.  
  12. require 'ostruct'
  13. class OpenStruct
  14. def add name
  15. last = self
  16. name.to_s.split('.').each do |n|
  17. o = OpenStruct.new
  18. last.send n.concat('=').intern, o
  19. last = o
  20. end
  21.  
  22. return last
  23. end
  24. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.