user3163916
user3163916

Reputation: 328

Ruby Inheritance Get Caller Class Name

I'm so lost. I know how to use caller to get the caller method, but what do you use the get the caller class?

For example:

class Testing
  def return_caller_class
    return caller_class
  end
end

class Parent

  attr_accessor :test_me

  def initialize      
    self.test_me =  Testing.new
  end

end

class Child < Parent
end

class GrandChild < Child
end

test_Parent = Parent.new
test_Child = Child.new
test_GrandChild = GrandChild.new

puts test_Parent.test_me.return_caller_class     => Parent
puts test_Child.test_me.return_caller_class      => Child
puts test_GrandChild.test_me.return_caller_class => GrandChild

Thank you!!!

Edit:

I've tried to do the following

class Testing
  def return_caller_class
    return caller[0][/`.*'/][1..-2]
  end
end

And the output is:

{"
"=>Parent}    
{"
"=>Child}
{"
"=>GrandChild}

To explain better about my question.

I would the output to display this instead

Parent
Child
GrandChild

Upvotes: 2

Views: 3611

Answers (2)

user2097847
user2097847

Reputation: 47

class Testing
  def return_caller_class
    self.class.name
  end
end

class ChildOne < Testing
end

class ChildTwo < Testing
end

result:
------------------------------------------------
>ChildOne.new.return_caller_class
 => "ChildOne"
>ChildTwo.new.return_caller_class
 => "ChildTwo"
>Testing.new.return_caller_class
 => "Testing"

Upvotes: 0

Kal
Kal

Reputation: 2664

I'm a bit out of my depth with this question, but I think you have made a few mistakes unrelated to the problem of getting the caller's class name. If I can help you with those things, at least you might be a step closer (if a solution is even possible)!

Firstly, it seems to me that you're calling return_caller_class from the main program object, not from one of those three objects you created. You have an object of class Testing inside an object of class Parent, but the method call is outside of both.

Secondly, the only reason you seem to be getting anything close to what you want (when you get output like "=>Parent} has nothing to do with the return_caller_class method. It seems as though you inadvertently created little hashes in the last three lines of your program (when you added => Parent, etc), which are being output with puts. (Confirmed here: Has #puts created a new hash?) If these are meant to be comments, they need a # before them.

PS. I found a link to this gem on another thread: https://github.com/asher-/sender. Might be worth checking out.

Upvotes: 2

Related Questions