From: Jamis Buck Date: 2004-01-06T04:59:06+09:00 Subject: Re: Basic Syntax for Extending Instances Lipper, Matthew wrote: >Hey everybody, > >Given the following extension to the Date class: > >class Date > > attr_accessor :date_precision > > class << self; alias_method :old_civil, :civil end > > def self.civil(*args) > #How to make this visible? > @date_precision = args.shift > puts "#{@date_precision}" if($VERBOSE) # >> DAY_OF_MONTH > > return old_civil(*args) > end > >end > >date = Date.civil("DAY_OF_MONTH",2004,2,5) > >#Doh! >puts date.date_precision # >> nil > >What is the proper syntax to make the date_precision attribute visible to >the caller? I'm still trying to wrap my head around the notion of open >classes and extending object instances... > >Matt > > > Well, it looks like the problem is that @date_precision is an "instance variable" of the object that represents the Date class, not of each instance of the Date class. What you should do is capture the result of old_civil (which would be an instance of the class) and then set the date_precision attribute on it, like this: d = old_civil( *args ) d.date_precision = args.shift return d See if that helps any. -- Jamis Buck jgb3@email.byu.edu ruby -h | ruby -e 'a=[];readlines.join.scan(/-(.)\[e|Kk(\S*)|le.l(..)e|#!(\S*)/) {|r| a << r.compact.first };puts "\n>#{a.join(%q/ /)}<\n\n"'