Basic Syntax for Extending Instances

  • Thread starter Lipper, Matthew
  • Start date
L

Lipper, Matthew

Hey everybody,

Given the following extension to the Date class:

class Date

attr_accessor :date_precision

class << self; alias_method :eek:ld_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
 
J

Jamis Buck

Hey everybody,

Given the following extension to the Date class:

class Date

attr_accessor :date_precision

class << self; alias_method :eek:ld_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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top