Class inherits from

I wanted to know if a class was an Active Record class. I couldn’t find an easy way to do it in Ruby so I monkey patches the Class object like so (assuming Person is an active record model object).

class Class
  def inherits_from?(klass, me=self)
    return false if me.nil?
    return true if me == klass
    inherits_from? klass, me.superclass

>> Person.inherits_from? ActiveRecord::Base
=> true
  1. Hi Mark,

    I think you can do this using ancestors as well mate:

    $> irb
    >> class A; end
    => nil
    >> class B < A; end
    => nil
    >> B.ancestors
    => [B, A, Object, Kernel]
    >> A.ancestors
    => [A, Object, Kernel]

    Hope this helps.



  2. Mark Mansour says:

    Great tip Marcus – I’m going to convert this code (or maybe just remove it)

  1. There are no trackbacks for this post yet.

Leave a Reply