Return to Snippet

Revision: 5833
at April 7, 2008 07:13 by neil


Updated Code
# 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

Revision: 5832
at April 7, 2008 06:34 by neil


Initial Code
# 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
  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.
  #
  def fill_in_blanks
  end

end

# --------------------------------------------------------------- 80 column rule

Initial URL

                                

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

Initial Title
initialized_by_hash

Initial Tags
object, ruby

Initial Language
Ruby