/ Published in: Ruby
provides a tidy way to add initialization by hash to new classes
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# Example: # class MyClass # # attr_accessor :configured, :defaulted, :derived # # initialized_by_hash # # def fill_in_blanks # raise 'configured attribute missing' unless @configured # @defaulted = 0 unless @defaulted # @derived = @configured + 1 # end # end # class Class # overrides the constructor of this class with one that expects a hash that # maps names of attributes to the initial values for those attributes # def initialized_by_hash define_method('initialize') do |*args| if 0 == args.length # do nothing. a blank object will be made elsif 1 == args.length and args[0].respond_to? :each_pair args[0].each_pair do |attribute, value| self.send "#{attribute}=", value end else raise "unexpected: #{args}" end fill_in_blanks end # invoked by the manufactured constructor after the values of the attributes # have been set to give the derived class a chance to initialize the new # object using the values given for construction. # define_method('fill_in_blanks') do end private :fill_in_blanks end end # --------------------------------------------------------------- 80 column rule