Posted By


neil on 04/07/08

Tagged


Statistics


Viewed 653 times
Favorited by 1 user(s)

initialized_by_hash


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

provides a tidy way to add initialization by hash to new classes


Copy this code and paste it in your HTML
  1. # Example:
  2. # class MyClass
  3. #
  4. # attr_accessor :configured, :defaulted, :derived
  5. #
  6. # initialized_by_hash
  7. #
  8. # def fill_in_blanks
  9. # raise 'configured attribute missing' unless @configured
  10. # @defaulted = 0 unless @defaulted
  11. # @derived = @configured + 1
  12. # end
  13. # end
  14. #
  15. class Class
  16.  
  17. # overrides the constructor of this class with one that expects a hash that
  18. # maps names of attributes to the initial values for those attributes
  19. #
  20. def initialized_by_hash
  21.  
  22. define_method('initialize') do |*args|
  23.  
  24. if 0 == args.length
  25. # do nothing. a blank object will be made
  26.  
  27. elsif 1 == args.length and args[0].respond_to? :each_pair
  28.  
  29. args[0].each_pair do |attribute, value|
  30.  
  31. self.send "#{attribute}=", value
  32. end
  33.  
  34. else raise "unexpected: #{args}"
  35. end
  36.  
  37. fill_in_blanks
  38. end
  39.  
  40. # invoked by the manufactured constructor after the values of the attributes
  41. # have been set to give the derived class a chance to initialize the new
  42. # object using the values given for construction.
  43. #
  44. define_method('fill_in_blanks') do
  45. end
  46.  
  47. private :fill_in_blanks
  48. end
  49.  
  50. end
  51.  
  52. # --------------------------------------------------------------- 80 column rule

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.