Basic Syntax for Extending Instances

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

Try:

class Date
attr_accessor :date_precision
class << self
alias_method :old_civil, :civil
def civil(*args)
precision = args.shift
_civil = old_civil(*args)
_civil.date_precision = precision
_civil
end
end
end

date = Date.civil(“DAY_OF_MONTH”, 2004, 2, 5)
puts date.date_precision

In your original code, you were adding @date_precision to the
singleton class Date (a “class instance” variable).

-austin

···

On Tue, 6 Jan 2004 04:42:26 +0900, 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
def 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
end

date = Date.civil(“DAY_OF_MONTH”,2004,2,5)

#Doh!
puts date.date_precision # >> nil


austin ziegler * austin@halostatue.ca * Toronto, ON, Canada
software designer * pragmatic programmer * 2004.01.05
* 14.48.27

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”’