On Mon, 9 May 2005, Hal Fulton wrote:

> Just thought I'd share a little concept that I find useful. Your comments
> are welcome.
>
> Sometimes objects are created with certain defaults.  One way to override
> them is with default values in the constructor (and often corresponding
> writer methods).
>
> But sometimes I "don't like" the default and want to change it (for this
> program/session).
>
> Often I use class-level accessors for that purpose.
>
> Here's a contrived example...
>
> Cheers,
> Hal
>
>
>   class Text
>
>     class << self
>       attr_accessor :color
>       Text.color = "black"
>     end
>
>     attr_accessor :color
>
>     def initialize(txt, color="black")
>   # Hint: You can improve this further by saying
>   # def initialize(txt, color=Text.color)
>       puts "#{color} text..."
>     end
>   end
>
>
>   # The old way...
>
>   a = Text.new("some")           # black
>   b = Text.new("random","blue")  # blue
>   c = Text.new("text")           # black
>   c.color = "blue"               # but now it's blue
>
>   # The new way...
>
>   Text.color = "blue"
>
>   e = Text.new("Ruby is cool")   # blue
>   f = Text.new("as dry ice")     # blue

i do this so much i built it in to my new traits lib (currently being
updated).  works like:

   harp:~ > cat a.rb
   require 'traits'

   class Text
     class_trait 'color' => 'black'
     trait 'color'

     def initialize opts = {}
       color( opts['color'] || opts[:color] || Text.color)
     end
   end

   Text::color = 'blue'
   p Text::new


   harp:~ > ruby a.rb
   #<Text:0xb75bb744 @color="blue">

i generally also allow modifing classes via the environment, eg:

   class Text
     class_trait 'color' => (ENV['TEXT_COLOR'] || 'black')
     trait 'color'
     def initialize opts = {}
       color( opts['color'] || opts[:color] || Text.color)
     end
   end

i'm using this in all cases except true constants - like PI.

cheers.


-a
-- 
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| renunciation is not getting rid of the things of this world, but accepting
| that they pass away. --aitken roshi
===============================================================================