* Create your FREE website now *

Object Initialization and Configuration

Tags:  

  • Parameters to initialize:
    • good if there are only a few common parameters that are used almost everytime
file = File.new( "foo.txt", "r" )
  • Hash parameter to initialize:
    • nice if there are only a few parameters and most parameters have defaults
    • nice because it names the parameters (more verbose)
    • order of parameters doesn't matter
db = Ramen.new ( :connection => my_connection, :engine => Sql2005 )
  • Context block
    • useful when there are many configuration options needed
    • can operate like a DSL by providing methods on the block parameter (conf in the example below)
    • can easily configure multiple closures
    • provides a lexical scope where the configuration object is valid, but the obj being created is not ready for use.
obj = SomeObject.new do | conf |
  conf.option1 = 'foo'
  conf.option2 = bar
  conf.select :everything
  conf.blockOne { |a| puts a }
  conf.blockTwo { |a| pp a }
end
  • Properties
    • poor style
      • not clear when the obj is ready for use.
      • configuration could get changed later by accidentally setting config properties at the wrong time.
obj = SomeObject.new
obj.option1 = 'foo'
obj.option2 = bar
obj.select :everything
  • Prototype
    • not commonly used
    • useful when creating lots of similar objects
    • automatically calls initialize_copy method on the new object
obj = another_object.clone   # copies everything: state, singleton methods, etc
obj = another_object.dup # copies state and tainted?
o = Object::const_get( class_name ).allocate
class_props.each_pair { |k,v| o.instance_eval "@#{k} = v" }





 RSS of this page

Written by:   Written by:   Version:   Last Edited By:   Modified