Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
Knowing which subclass called a superclass class method
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Rob Boellaard, post: 4609724"] Hi David, This time I really made the class ;-) class S attr_accessor :my_ivar def self.inherited(c) c.class_eval { @my_ivar = self.name } end def initialize puts "In S initialize, my_ivar = #{@my_ivar}" super end def self.do_something puts "In S class-method do_something, my_ivar = #{@my_ivar}" end end and, require "s" class B < S def initialize super end def show_my_ivar puts "In show_my_ivar " + @my_ivar end end when I do B.do_something, @my_ivar is "B" as it should but if I do B.new, my_ivar is nil To solve it I can modify initialize like: def initialize @my_ivar = self.class.to_s puts "In S initialize, my_ivar = #{@my_ivar}" super end and b = B.new puts b.show_my_ivar works properly. But as this is a simplification, in my real app I need a few lines of code to set @my_ivar, and I 'd rather not have too much duplicate code. I guess what I am trying for is to configure a variable, using the name of the subclass, that is readily available to both class methods and instance methods. thanks a lot, Rob [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
Knowing which subclass called a superclass class method
Top