Get the class name of the class who called the parent instance method.

36 views
Skip to first unread message

Alexandre Calvão

unread,
Oct 9, 2014, 11:18:14 PM10/9/14
to rubyonra...@googlegroups.com
Is there a way for me to do that on ruby ?

class Foo
  def self.class_name
  end
end

class Bar < Foo
end

class Tar < Foo
end

Bar.class_name 
= 'Bar'

Tar.class_name
= 'Tar'

I want to get the class name of the class who called the instance method from the parent class.

I tried the code above and it keeps getting me 'Class' as the result.

Is that possible in ruby ?

[]`s

===================
Alexandre Mondaini Calvão

"Nossa recompensa se encontra no esforço e não no resultado. Um esforço total é uma vitória completa." [Ghandi]

Alexandre Calvão

unread,
Oct 9, 2014, 11:27:10 PM10/9/14
to rubyonra...@googlegroups.com
Is not instance method, is class method... My bad


===================
Alexandre Mondaini Calvão

"Nossa recompensa se encontra no esforço e não no resultado. Um esforço total é uma vitória completa." [Ghandi]

Mike

unread,
Oct 10, 2014, 12:31:14 PM10/10/14
to rubyonra...@googlegroups.com
You might want something like this.



class Foo
end

Foo.instance_eval do
  def class_name
    self.name
  end
end


class Bar < Foo
end

class Tar < Foo
end

puts Foo.class_name
#=> Foo

puts Bar.class_name
#=> Bar

puts Tar.class_name
#=> Tar

Alexandre Calvão

unread,
Oct 11, 2014, 4:55:21 PM10/11/14
to rubyonra...@googlegroups.com
Thanks Mike.


===================
Alexandre Mondaini Calvão

"Nossa recompensa se encontra no esforço e não no resultado. Um esforço total é uma vitória completa." [Ghandi]

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/87114137-56e1-4a12-97f6-ef2f0511b988%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Rob Biedenharn

unread,
Oct 13, 2014, 11:32:32 AM10/13/14
to rubyonra...@googlegroups.com
Why do anything fancy? An instance know which class it is. Just ask for the .class and then get that Class's .name.

irb2.1.3> class Foo; end
#2.1.3 => nil
irb2.1.3> class Bar < Foo; end
#2.1.3 => nil
irb2.1.3> class Baz < Foo; end
#2.1.3 => nil
irb2.1.3> foo = Foo.new
#2.1.3 => #<Foo:0x007f98940cb528>
irb2.1.3> foo.class.name
#2.1.3 => "Foo"
irb2.1.3> bar = Bar.new
#2.1.3 => #<Bar:0x007f98940b55c0>
irb2.1.3> bar.class.name
#2.1.3 => "Bar"
irb2.1.3> baz = Baz.new
#2.1.3 => #<Baz:0x007f98940b38d8>
irb2.1.3> baz.class.name
#2.1.3 => "Baz"

-Rob

Reply all
Reply to author
Forward
0 new messages